Bean定義:
1 public class GetM100DataResponse {
2 private String service;//接口代碼
3 private String sessionId;//會話Id
4 private String errorCode;//錯誤碼
5 private String errorMsg;//錯誤消息
6 private String summary;//摘要
7
8 private List<M100DataObject> dataPoints; //數據列表
9
10 //get set 略
11 }
1 public class M100DataObject {
2 private String dataType; //數據類型 String
3 private String sendDateTime; //發送時間 String
4 private M100DataObjectKV dataKV; //數值對象 Object
5 private String serviceNo; //用戶服務號 String
6 private Integer userSeq; //用戶序號 Integer
7 private String eqmtNo; //設備號 String
8
9 //get set 略
10 }
JSON字符串:
1 {
2 "dataPoints":[
3 {
4 "dataKV":{
5 "pulse":"103",
6 "measurementTime":"2015-12-02 12:06:32",
7 "low":"91",
8 "high":"126",
9 "id":"d750fed2-0c95-4722-92ac-3078fa34390b"
10 },
11 "dataType":"1",
12 "eqmtNo":"",
13 "sendDateTime":"2015-12-02 12:06:33",
14 "serviceNo":"5716b0badb4b426cbfaaebb1be7d57b3",
15 "userSeq":"1"
16 }
17 ],
18 "diagResult":"",
19 "errorCode":"1",
20 "errorMsg":"成功!",
21 "propose":"",
22 "service":"GET_M100_DATA",
23 "sessionId":"1",
24 "summary":""
25 }
轉換代碼如下:
1 public static JsonConfig getDecodeJSONConfig(){
2 JsonConfig jsonConfig = new JsonConfig();
3 jsonConfig.registerJsonValueProcessor(String.class, new JsonValueProcessor() {
4 public Object processArrayValue(Object value,
5 JsonConfig arg1) {
6 // TODO Auto-generated method stub
7 return process(value);
8 }
9
10 public Object processObjectValue(String key,
11 Object value, JsonConfig arg2) {
12 // TODO Auto-generated method stub
13 return process(value);
14 }
15
16 public Object process(Object value) {
17 try {
18 if (value instanceof String) {
19 return URLDecoder.decode(value.toString(),"UTF-8");
20 }
21 return value == null ? "" : value.toString();
22 } catch (Exception e) {
23 return "";
24 }
25 }
26 }
27 );
28 return jsonConfig;
29 }
30 public GetM100DataResponse parseData(String resData){//resData為JSON字符串
31 JsonConfig jsonConfig = getDecodeJSONConfig();
32 JSONObject json = JSONObject.fromObject(resData, jsonConfig);
33 /*
34 * 在JSONObject.toBean的時候,如果轉換的類中有集合,
35 * 可以先定義:Map<String, Class> classMap = new HashMap<String, Class>();
36 * 然后在classMap中put你要轉換的類中的集合名,如:
37 */
38 Map<String, Class> classMap = new HashMap<String, Class>();
39 classMap.put("dataPoints", M100DataObject.class);//dataPoints 為 屬性名稱
40 /*
41 * 然后在toBean()的時候把參數加上, 如:
42 */
43 GetM100DataResponse response = (GetM100DataResponse)JSONObject.toBean(json, GetM100DataResponse.class, classMap);
44 return response;
45 }
over

