Java:Json与List对象的相互转换

方法一:谷歌的Gson.jar:

……list转换为json

1 Gson gson = new Gson();
2 List<Person> persons = new ArrayList<Person>();
3 String str = gson.toJson(persons);

……json转换为list

1 Gson gson = new Gson();
2 List<Person> persons = gson.fromJson(str, new TypeToken<List<Person>>(){}.getType());

 

方法二:阿里的fastJson.jar:

导入包
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

……list转换为json

1 List<CustPhone> list = new ArrayList<CustPhone>();
2 String str=JSON.toJSON(list).toString();

……json转换为list

1 List<Person> list = new ArrayList<Person>();
2 list = JSONObject.parseArray(jasonArray, Person.class);

 

实用举例:

1 参数:JSONObject params
2 
3 List<DlvOrderDto> dlvOrderDtos = new ArrayList<>();
4 String str = JSON.toJSON(params.get("rowData")).toString();
5 dlvOrderDtos = JSONObject.parseArray(str, DlvOrderDto.class);

 

本篇记录参考来源:

https://zhuanlan.zhihu.com/p/44664185

 

 
posted @ 2021-06-30 10:58  初入其境  阅读(7250)  评论(0)    收藏  举报