簡單JSON對象操作
1.將String對象轉換爲JSON對象
JSONObject jsonObject = JSONObject.parseObject(resp);
2.將JSON對象序列化爲String對象
String jsonString = JSON.toJSONString(jsonObject);
3.將String對象反序列化爲JAVA對象
CaseConfigDto caseConfigDto = JSON.parseObject(jsonString, CaseConfigDto.class);
4.將JAVA對象轉String對象
String string = JSON.toJSONString(caseConfigDto);
JSON數組操作
1.從String對象中獲取JSONArray
JSONArray jsonArray = JSONObject.parseObject(resp).getJSONArray("data");
2.JSON數組轉對象數組
List<CaseConfigDto> list = JSON.parseArray(jsonArray.toString(),CaseConfigDto.class);
3.對象數組轉JSON數組
JSONArray array= JSONArray.parseArray(JSON.toJSONString(list));
JSON轉Map
Map<String, String> params = JSONObject.parseObject(obj.toJSONString(), new TypeReference<Map<String, String>>(){});
public static Map<String,Object> jsonObject2Map(JSONObject jsonObject){
Iterator it = jsonObject.entrySet().iterator();
Map<String, Object> map = new HashMap<>();
while (it.hasNext()) {
Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
map.put(entry.getKey(), entry.getValue());
}
return map;
}
MAP轉JSON
JSONObject json = new JSONObject(map);