前言
由于接收原來(lái)的老項(xiàng)目并進(jìn)行維護(hù),之前的http請(qǐng)求是使用Apache Jakarta Common下的子項(xiàng)目HttpClient蜘腌,因此使用了 List<NameValuePair> 方式來(lái)創(chuàng)建參數(shù)隊(duì)列必盖,然后通過(guò)一個(gè)字符串處理的工具類拌牲,生成的post請(qǐng)求體格式大致如:
a=b&c=d&e=f
但是由于服務(wù)器api變更俱饿,需要將請(qǐng)求體的格式變成json格式,因此上面的請(qǐng)求參數(shù)要變成:
{"a":"b","c":"d","e":"f"}
但是如果將List<NameValuePair>直接通過(guò)Jackson或者Gson等第三方工具的轉(zhuǎn)json的開(kāi)源類庫(kù)去轉(zhuǎn)換為json格式的話塌忽,轉(zhuǎn)出來(lái)的json格式如:
[{"name":"a","value":"b"},{"name":"c","value":"d"},{"name":"e","value":"f"}]
如下面代碼所示:
public class RequestParams {
/**請(qǐng)求地址*/
public String url;
/**請(qǐng)求參數(shù)集合*/
public List<NameValuePair> params;
}
/**
* 帳號(hào)登錄
*
* @param userName 賬號(hào)名
* @param password 密碼
* @param days 記住密碼天數(shù):days>0定期超時(shí)拍埠;days=-2永不失效;
* days=-1永久記住密碼(30天沒(méi)有操作則失效)
* @param deviceId 賬戶在設(shè)備上的唯一標(biāo)識(shí)符(機(jī)器碼或mac地址)
* @param appId 應(yīng)用id
* @return
*/
public static RequestParams loginParams(String userName, String password, int days, String deviceId, int appId) {
RequestParams params = new RequestParams();
params.url = LOGIN_URI;
params.params = new ArrayList<NameValuePair>();
params.params.add(new BasicNameValuePair("userName", userName));
params.params.add(new BasicNameValuePair("password", password));
params.params.add(new BasicNameValuePair("days", String.valueOf(days)));
params.params.add(new BasicNameValuePair("deviceId", deviceId));
params.params.add(new BasicNameValuePair("appId", String.valueOf(appId)));
params = addcommonParams(params, LOGIN_URI, appId);
return params;
}
在請(qǐng)求的時(shí)候土居,將List<NameValuePair> params取出來(lái)枣购,然后使用JSONUtil工具類轉(zhuǎn)換成json格式,代碼如下所示:
String request=JSONUtil.toJSON(requestParams.params);
其中換成json格式的工具類JSONUtil,該工具類使用了jackjson的第三方j(luò)son解析庫(kù)装盯,代碼如下所示:
import android.util.Log;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
/**
* JSON轉(zhuǎn)換工具類
*
* @author OuyangPeng
* @version [1.0.0.0, 2016-3-23]
*/
public class JSONUtil {
private static String TAG = JSONUtil.class.getName();
private static ObjectMapper mapper = new ObjectMapper();
static {
//對(duì)于為null的字段不進(jìn)行序列化
mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
//對(duì)于未知屬性不進(jìn)行反序列化
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//無(wú)論對(duì)象中的值只有不為null的才進(jìn)行序列化
mapper.setSerializationInclusion(Include.NON_NULL);
}
/**
* 把對(duì)象轉(zhuǎn)化成json字符串
*
* @param obj
* @return
*/
public static String toJSON(Object obj) {
if (obj == null) {
return null;
}
Writer write = new StringWriter();
try {
mapper.writeValue(write, obj);
} catch (JsonGenerationException e) {
Log.e(TAG, e.toString() + obj);
} catch (JsonMappingException e) {
Log.e(TAG, e.toString() + obj);
} catch (IOException e) {
Log.e(TAG, e.toString() + obj);
}
return write.toString();
}
/**
* JSON字符串轉(zhuǎn)成對(duì)象
*
* @param jsonStr
* @param classType
* @return
*/
public static <T> T fromJSON(String jsonStr, Class<T> classType) {
if (isEmptyOrNull(jsonStr)) {
return null;
}
T t = null;
try {
t = mapper.readValue(jsonStr.getBytes("utf-8"), classType);
} catch (JsonParseException e) {
Log.e(TAG, e.toString() + ", jsonStr:" + jsonStr + ", classType:" + classType.getName());
} catch (JsonMappingException e) {
Log.e(TAG, e.toString() + ", jsonStr:" + jsonStr + ", classType:" + classType.getName());
} catch (IOException e) {
Log.e(TAG, e.toString() + ", jsonStr:" + jsonStr + ", classType:" + classType.getName());
}
return t;
}
/**
* JSON字符串轉(zhuǎn)化成集合
*
* @param jsonStr
* @return
*/
public static <T> T toCollection(String jsonStr, Class<?> collectionClass, Class<?>... elementClasses) {
if (isEmptyOrNull(jsonStr)) {
return null;
}
T t = null;
try {
t = mapper.readValue(jsonStr.getBytes("utf-8")
, mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses));
} catch (JsonParseException e) {
e.printStackTrace();
Log.e(TAG, e.toString() + ", jsonStr:" + jsonStr);
} catch (JsonMappingException e) {
e.printStackTrace();
Log.e(TAG, e.toString() + ", jsonStr:" + jsonStr);
} catch (IOException e) {
Log.e(TAG, e.toString() + ", jsonStr:" + jsonStr);
}
return t;
}
public static Object get(String jsonStr, String key) {
Object obj = null;
try {
JSONObject jsonObj = new JSONObject(jsonStr);
obj = jsonObj.get(key);
} catch (JSONException e) {
e.printStackTrace();
}
return obj;
}
/**
* 判斷字符串是否為null或者""
*/
public static boolean isEmptyOrNull(String content) {
if (content == null || content.equals("")) {
return true;
}
return false;
}
}
使用上面的代碼將List<NameValuePair> params請(qǐng)求參數(shù)集合轉(zhuǎn)換為json后坷虑,(不標(biāo)準(zhǔn))格式如下所示:
[{"name":"userName","value":"13911002200"},{"name":"password","value":"123456"},{"name":"days","value":"-1"},{"name":"deviceId","value":"02:00:00:00:00:00"},{"name":"appId","value":"11"},{"name":"mac","value":"02:00:00:00:00:00"},{"name":"timestamp","value":"2016-03-26 10:24:35"},{"name":"sign","value":"b2873caa5735d16535ff827ee2701cd1"}]
好吧,這樣的格式完全不是標(biāo)準(zhǔn)的json格式埂奈,服務(wù)器那邊需要的(標(biāo)準(zhǔn))json格式是:
{"deviceId":"02:00:00:00:00:00","password":"123456","days":"-1","sign":"b2873caa5735d16535ff827ee2701cd1","mac":"02:00:00:00:00:00","timestamp":"2016-03-26 10:24:35","appId":"11","userName":"13911002200"}
另外一個(gè)請(qǐng)求參數(shù)隊(duì)列轉(zhuǎn)后的json格式如下迄损,(不標(biāo)準(zhǔn)):
[{"name":"accountId","value":"2384403"},{"name":"password","value":"123456"},{"name":"ticket","value":"{"accountId":"2384403","appId":"11","loginName":"1302200","userName":"U12384403","email":"","mobilePhone":"1302200","timestamp":"2016-03-26","maxAge":-1,"ip":"","sign":"4109c59eff52a924e74be3623ecab27d","deviceId":"02:00:00:00:00:00"}"},{"name":"appId","value":"11"},{"name":"mac","value":"02:00:00:00:00:00"},{"name":"timestamp","value":"2016-03-26 10:26:01"},{"name":"sign","value":"22070f51197c15d256764a2de499ef85"}]
服務(wù)器那邊需要的另外一個(gè)請(qǐng)求參數(shù)隊(duì)列轉(zhuǎn)后的(標(biāo)準(zhǔn))json格式如下所示:
{"timestamp":"2016-03-26 10:26:01","password":"123456","appId":"11","ticket":"{"accountId":"2384403","appId":"11","loginName":"1302200","userName":"U12384403","email":"","mobilePhone":"1302200","timestamp":"2016-03-26","maxAge":-1,"ip":"","sign":"4109c59eff52a924e74be3623ecab27d","deviceId":"02:00:00:00:00:00"}","sign":"22070f51197c15d256764a2de499ef85","accountId":"2384403","mac":"02:00:00:00:00:00"}
好的,現(xiàn)在來(lái)說(shuō)一說(shuō)解決方法:
step1:將List<NameValuePair> params進(jìn)行遍歷然后丟在同一個(gè)Map集合中去
step2:使用JONUtil對(duì)Map集合進(jìn)行轉(zhuǎn)換成json格式字符串
代碼如下所示:
/*** 將請(qǐng)求參數(shù)轉(zhuǎn)換為json格式*/
Map map=new HashMap();
for (int i=0;i<requestParams.params.size();i++){
NameValuePair nameValuePair=requestParams.params.get(i);
map.put(nameValuePair.getName(),nameValuePair.getValue());
}
String request=JSONUtil.toJSON(requestParams.params);
String jsonRequest=JSONUtil.toJSON(map);
LogUtil.d(TAG, "發(fā)送給服務(wù)器的內(nèi)容為:加密前的data::" + request);
LogUtil.d(TAG, "發(fā)送給服務(wù)器的內(nèi)容為:加密前的 json data::" + jsonRequest);
打印出來(lái)的日志如下所示:
發(fā)送給服務(wù)器的內(nèi)容為:加密前的data::[{"name":"userName","value":"13011002200"},{"name":"password","value":"123456"},{"name":"days","value":"-1"},{"name":"deviceId","value":"02:00:00:00:00:00"},{"name":"appId","value":"11"},{"name":"mac","value":"02:00:00:00:00:00"},{"name":"timestamp","value":"2016-03-26 10:24:35"},{"name":"sign","value":"b2873caa5735d16535ff827ee2701cd1"}]
發(fā)送給服務(wù)器的內(nèi)容為:加密前的 json data::{"deviceId":"02:00:00:00:00:00","password":"123456","days":"-1","sign":"b2873caa5735d16535ff827ee2701cd1","mac":"02:00:00:00:00:00","timestamp":"2016-03-26 10:24:35","appId":"11","userName":"13011002200"}
發(fā)送給服務(wù)器的內(nèi)容為:加密前的data::[{"name":"accountId","value":"2384403"},{"name":"password","value":"123456"},{"name":"ticket","value":"{\"accountId\":\"2384403\",\"appId\":\"11\",\"loginName\":\"130***2200\",\"userName\":\"U12384403\",\"email\":\"\",\"mobilePhone\":\"130***2200\",\"timestamp\":\"2016-03-26\",\"maxAge\":-1,\"ip\":\"\",\"sign\":\"4109c59eff52a924e74be3623ecab27d\",\"deviceId\":\"02:00:00:00:00:00\"}"},{"name":"appId","value":"11"},{"name":"mac","value":"02:00:00:00:00:00"},{"name":"timestamp","value":"2016-03-26 10:26:01"},{"name":"sign","value":"22070f51197c15d256764a2de499ef85"}]
發(fā)送給服務(wù)器的內(nèi)容為:加密前的 json data::{"timestamp":"2016-03-26 10:26:01","password":"123456","appId":"11","ticket":"{\"accountId\":\"2384403\",\"appId\":\"11\",\"loginName\":\"130***2200\",\"userName\":\"U12384403\",\"email\":\"\",\"mobilePhone\":\"130***2200\",\"timestamp\":\"2016-03-26\",\"maxAge\":-1,\"ip\":\"\",\"sign\":\"4109c59eff52a924e74be3623ecab27d\",\"deviceId\":\"02:00:00:00:00:00\"}","sign":"22070f51197c15d256764a2de499ef85","accountId":"2384403","mac":"02:00:00:00:00:00"}