json与对象互转:json转实体类、实体类转json、json转List、List转json
生活随笔
收集整理的這篇文章主要介紹了
json与对象互转:json转实体类、实体类转json、json转List、List转json
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
- 使用fastjson和Gson實現:實體類與json互轉,List與json互轉
- 1. 實體類轉json數據
- 1.1 fastjson:
- 1.2 Gson:
- 2. json轉實體類
- 2.1 fastjson:
- 2.2 Gson:
- 3. List集合轉json
- 3.1 fastjson:
- 3.2 Gson:
- 4. JSON轉List集合
- 4.1 fastjson:
- 4.2 Gson:
使用fastjson和Gson實現:實體類與json互轉,List與json互轉
1. 實體類轉json數據
1.1 fastjson:
String json = JSONObject.toJSONString(resultData); System.err.println(json); JSONObject jsonObject = JSON.parseObject(json); System.err.println(jsonObject.get("message"));1.2 Gson:
Gson gson = new Gson(); String str = gson.toJson(resultData); System.err.println(str);2. json轉實體類
2.1 fastjson:
ResultData resultData = json.toJavaObject(ResultData.class);效果:
2.2 Gson:
BoTaskPlan bo = new Gson().fromJson(json.toString(),BoTaskPlan.class);Gson包依賴如下:
<dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.8.6</version></dependency>效果:
3. List集合轉json
3.1 fastjson:
JSONArray array = JSONArray.parseArray(JSON.toJSONString(list)); System.err.println(array); JSONObject json = (JSONObject) array.get(0); System.err.println(json);3.2 Gson:
Gson gson = new Gson(); String str = gson.toJson(list); System.err.println(str);4. JSON轉List集合
4.1 fastjson:
JSONArray array = JSONArray.parseArray(JSON.toJSONString(list)); System.err.println(array); List<Map> list2 = array.toJavaList(Map.class);4.2 Gson:
List<Student> arrayList = new ArrayList<>(); arrayList = gson.fromJson(str, new TypeToken<List<Student>>() {}.getType());總結
以上是生活随笔為你收集整理的json与对象互转:json转实体类、实体类转json、json转List、List转json的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C和C++混合编程(__cplusplu
- 下一篇: Studio 3T for MongoD