Java JSONObject 常用5种转换json方法示例
Java JSONObject 常用5种转换json方法应用示例
前提环境(pom中引用包)
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
1、原生生成json数据格式
JSONObject Person = new JSONObject();
Person.put("name","小白实验室");
Person.put("age","18");
Person.put("school","永远18");
Person.put("local","辽宁");
System.out.println(Person.toJSONString());
结果:{"name":"小白实验室","age":"18","school":“永远18”,"local":"辽宁"}
2、hashMap数据结构生成
Map<String,Object> map = new HashMap<>();
map.put("name","小白实验室");
map.put("age",18);
map.put("hobby","实验");
System.out.println(new JSONObject(map).toJSONString());
结果:{"name":"小白实验室","age":"18","hobby":"实验"}
3、实体生成
Student stud = new Student();
stud.setAge("18");
stud.setName("小白实验室");
stud.setSchool("辽宁");
JSONObject stud_json = (JSONObject) JSON.toJSON(stud);
System.out.println(stud_json.toString());
结果:{"Age":"18","name":"小白实验室","school":"辽宁"}
4、JSON字符串转换成JSON对象
String studentString = "{\"id\":1,\"age\":18,\"name\":\"小白实验室\"}";
JSONObject jsonObject1 = JSONObject.parseObject(stuString);
System.out.println(jsonObject1);
5、list对象转listJson
ArrayList<Student> studentLsit = new ArrayList<>();
Student student1 = new Student();
student1.setId(1);
student1.setAge("18");
student1.setName("小白实验室");
studentLsit.add(student1);
Student student2 = new Student();
student2.setId(2);
student2.setAge("20");
student2.setName("小白实:;验室");
studentLsit.add(student2);
list转json字符串
String string = JSON.toJSON(studentLsit).toString();
System.out.println(string);
json字符串转listJson格式
JSONArray jsonArray = JSONObject.parseArray(string);
System.out.println(jsonArray);
list 转 JSONArray
JSONArray jsonArray = new JSONArray(shareConfirmList);
// JSONArray 转 list
List<T> shareConfirmList = jsonArray.toJavaList(T.class);