本文中使用的JSON拼接与解析采用第三方包,网址路径:Maven Repository: Search/Browse/Explore (mvnrepository.com)
格式1:[{"name":"1","value":2}]
拼接方法:
private String jointJson1() {
String jsonArray = "";
List<Map<Object, Object>> frameJsonList = new ArrayList<>();
Map<Object, Object> st = new HashMap<>();
st.put("name", "1");
st.put("value", 2);
frameJsonList.add(st);
jsonArray = JSON.toJSONString(frameJsonList);
return jsonArray;
}
代码中采用key-value组成数据,将数据加入到List中,通过第三方包自带方法即可拼成JSON字符串;
解析方法:
private static void analysisJson1(String date) {
List dateList = JSON.parseObject(date, List.class);
for (JSONObject jsondate : dateList) {
NameValue json = JSON.parseObject(String.valueOf(jsondate), NameValue.class);
String name = json.getName();
int value = json.getValue();
logger.info("name:" + name + " value:" + value);
}
}
class NameValue {
private String name;
private int value;
public NameValue(String name, int value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
格式2:{1:[{"readValue":"read","setValue":"set","name":"n"}]}
拼接方法:
private String jointJson2() {
String jsonArray = "";
Map<Integer, List<Map<Object, Object>>> jsonMap = new HashMap<>();
List<Map<Object, Object>> frameJsonList = new ArrayList<>();
Map<Object, Object> st = new HashMap<>();
st.put("readValue", "read");
st.put("setValue", "set");
st.put("name", "n");
frameJsonList.add(st);
jsonMap.put(1, frameJsonList);
jsonArray = JSON.toJSONString(jsonMap);
return jsonArray;
}
解析方法:
public void analysisJson(String date) {
Map<String, Object> map = JSON.parseObject(date, Map.class);
for (String frameId : map.keySet()) {
String ojStr = map.get(frameId).toString();
List<JSONObject> dateList = JSON.parseObject(ojStr, List.class);
for (JSONObject da : dateList) {
New3Parameter da3 = JSON.parseObject(String.valueOf(da), New3Parameter.class);
String name = da3.getName();
String setValue = da3.getSetValue();
String readValue = da3.getReadValue();
}
}
}
格式2的JSON也可以看作是key-value,只不过这个value比较复杂;可以将value提取出后,按照格式1的解析方法,就可以解析出其中包含的值。