jackson-嵌套json转换为java对象
话不多说,上代码:
Json > java bean:
String data = "{\"SN\":\"863703030059864\",\"CMD\":\"UBD\",\"FLOW\":\"89\",\"TIME\":\"0\",\"STATUS\":\"1\",\"DATAS\":{\"data0\":\"863703030059864\",\"data1\":\"460068162083055\",\"data2\":\"69 \",\"data3\":\"27\",\"data4\":\"356\",\"data5\":\"0\",\"data6\":\"0\",\"data7\":\"0\",\"data9\":\"1\",\"data10\":\"1\",\"data11\":\"246.54,175.40\",\"data12\":\"-887,31,-385\",\"data13\":\"0,0,24,15,15\"}}"
JsonNode rootNode = null,childrenNode = null;
try {
rootNode = objectMapper.readTree(data);
childrenNode = rootNode.path("DATAS");
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
这样,就不用写java对象,来存json了,直接可以用:
rootNode.get("CMD").asText()
childrenNode.get("data0").asText()
直接拿到你需要的字段了,还是很方便和高效的;
java bean > Json :
String result = {"CMD": "ACT","SN": "863703030059864", "DATAS": {"status": "1","travel_switch": "1","hinge": "0","beacon_interval":"24","level_interval": "15","travel_interval": "15"}} }
这里需要两个java对象来set数据,
Data data = new Data();
Datas datas = new Datas();
String result = {"CMD": "ACT","SN": "863703030059864", "DATAS": {"status": "1","travel_switch": "1","hinge": "0","beacon_interval":"24","level_interval": "15","travel_interval": "15"}} }
datas.setStatus("1");
datas.setTravel_switch("1");
datas.setHinge("0");
datas.setBeacon_interval("24");
datas.setLevel_interval("15");
datas.setTravel_interval("15");
data.setCMD("ACT");
data.setSN("863703030059864");
data.setDATAS(datas);
String result = null;
try {
result = objectMapper.writeValueAsString(data);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Jackson跟我们之前用的(import com.google.gson.Gson; 和 import net.sf.json.JSONObject;)不太一样,但是新的体验不是很美妙吗,嘿嘿~