主流Java json 库的实现分析: https://blog.csdn.net/u013063153/article/details/73163624
1.fastjson
主要处理对象是JSON,通过JSON.toJSONString(obj) 来将数据转为json 格式,通过 JSON.parseObject 将数据转换为所需格式
其他类型转为json 类型的String
String json = JSON.toJSONString(model); // serializes model to Json
jsonString 转其他类型
Model model2 = JSON.parseObject(json, Model.class); // deserializes json into model2
其他类型转jsonObject
JSONObject jb = JSON.parseObject(String text);
2.gson
主要处理对象是Gson ,通过Gson.toJson(obj) 转为json 格式 ,通过Gson.fromJson 转换为所需的java对象
String 类型转 gson, gson 转其他类型
Gson gson = new Gson();
String json = gson.toJson(str);
System.out.println(json);
String fromJson = gson.fromJson(json, String.class);
System.out.println(fromJson);
json 转 map
Map<String,Object> map = new Gson().fromJson(urlGetToQualifiedPath, new TypeToken<HashMap<String,Object>>(){}.getType());//gson
3.json-lib
JSONObject fromObject = JSONObject.fromObject(JsonMessage.str);
System.out.println(fromObject);
String bean = (String) JSONObject.toBean(fromObject, String.class);
System.out.println(bean);
4.jackson
主要是ObjectMapper对象
json 转 map
String responseMessageGet = TestOKHttp.getResponseMessageGet(url);
ObjectMapper mapper = new ObjectMapper();
Map<String,String> reMap = null;
reMap = mapper.readValue(responseMessageGet, new TypeReference<Map<String,Object>>(){});
map 转 json
ObjectMapper mapper = new ObjectMapper();
String jsonReturn = null;
jsonReturn = mapper.writeValueAsString(map);