您的位置:首页 > Web前端 > JavaScript

自己封装Jackson的工具类——JsonUtil

2015-05-07 12:03 405 查看

使用Jackson

import android.text.TextUtils;
import android.util.Log;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.io.IOException;

/**
* Created by kevin on 15-1-24.
*/
public class JsonSendUtil {
private static ObjectMapper mapper;
private static final String TAG = "JsonSendUtil";

public static final String SEND_FAILED = "1";

static {
mapper = new ObjectMapper();
//mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
}

public static synchronized  <T, U> U sendJsonForGetResult(T entity, Class<U> resultClass, String url) {
String json;
U resultEntity = null;
try {
json = mapper.writeValueAsString(entity);
if (json != null) {
String result = CustomHttpURLConnection.PostJsonToWebByHttpURLConnection(url, json);
Log.d(TAG,"result: " + result +"  Json: "+json);
if (!TextUtils.isEmpty(result)) {
resultEntity = mapper.readValue(result, resultClass);
}
}
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return resultEntity;
}
}


使用

import com.fasterxml.jackson.annotation.JsonProperty;

import cn.rspread.im.IMApplication;

/**
* Created by kevin on 15-1-23.
*/
public class LoginOrRegisterEntity {
//{"phone":{"ApiKey":"123456","phone":"861860302645"}}

private Phone phone;

public LoginOrRegisterEntity(String phoneNumber) {
this.phone = new Phone();
phone.setApiKey(IMApplication.API_KEY);
phone.setPhone(phoneNumber);

}

public Phone getPhone() {
return phone;
}

public void setPhone(Phone phone) {
this.phone = phone;
}

public static class Phone {

@JsonProperty("ApiKey")
private String apiKey;
private String phone;

public String getApiKey() {
return apiKey;
}

public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}
}
}


import com.fasterxml.jackson.annotation.JsonProperty;

/**
* Created by kevin on 15-1-23.
*/
public class LoginOrRegisterResultEntity {
//{"SendSmsResult":"1"}
@JsonProperty("SendSmsResult")
private String sendSmsResult;

public String getSendSmsResult() {
return sendSmsResult;
}

public void setSendSmsResult(String sendSmsResult) {
this.sendSmsResult = sendSmsResult;
}
}


调用

public static boolean sendLoginOrRegister(String phone) {
if (TextUtils.isEmpty(phone)) {
return false;
}

loginPhoneNumber = phone;

LoginOrRegisterEntity loginOrRegisterEntity = new LoginOrRegisterEntity(phone);
LoginOrRegisterResultEntity resultEntity = JsonSendUtil.sendJsonForGetResult(loginOrRegisterEntity, LoginOrRegisterResultEntity.class, LOGIN_URL);
if (resultEntity==null) {
return false;
}

return ("1").equals(resultEntity.getSendSmsResult());
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: