java中对象转json,json转list,json转map
在IDEA中的springboot项⽬⾥写的⼀个测试例⼦,新建User类,四个字段,Long id , String password,String userName,int age; 以及带参构造,toString⽅法在l中添加 net.sf.json-lib  依赖:
1<!-- 对象转json依赖包 -->
2<!-- mvnrepository/artifact/net.sf.json-lib/json-lib -->
json转换对象3<dependency>
4<groupId>net.sf.json-lib</groupId>
5<artifactId>json-lib</artifactId>
6<version>2.4</version>
7<!--不加下⾯这⼀项会报错,是因为json-lib⽀持版本是jdk1.5,所以要指定下版本-->
8<classifier>jdk15</classifier>
9</dependency>
json转换测试类:
1package com.lch.springboot04.jsonparse;
2
3import com.lch.springboot04.domain.User;
4import net.sf.json.JSONArray;
5import net.sf.json.JSONObject;
6
7import java.util.*;
8
9/**
10 * 对象转换为json数据测试,通过net.sf.json-lib.jar
11*/
12public class JsonParse {
13
14public static void main(String[] args) {
15/**
16        *  object 转为json数组 :数组,对象,map,list,list<Map<String,Object>> 都可以;
17        *  object 转为json字符串:只有⾃定义对象和 map可以转换,其他都不能这样转;
18*/
19
20        String[] arr = {"a", "b", "c"};
21        System.out.println("string数组转为json数组" + JSONArray.fromObject(arr)); //["a","b","c"]
22//        System.out.println("string数组转为json字符串"+ JSONObject.fromObject(arr).toString()); //⽆法转换:'object' is an array. Use JSONArray instead
23
24//java⾃定义对象转json
25        User jack = new User("123", "jack", 18);
26        System.out.println("Java对象转为json数组" + JSONArray.fromObject(jack));
27//结果:[{"age":18,"id":0,"password":"123","userName":"jack"}]
28        System.out.println("Java对象转为json字符串" + JSONObject.fromObject(jack).toString());
29//结果:{"age":18,"id":0,"password":"123","userName":"jack"}
30
31//list转json
32        User tom = new User("456", "tom", 20);
33        List<User> userList = new ArrayList<>();
34        userList.add(jack);
35        userList.add(tom);
36        System.out.println("list转为json数组" + JSONArray.fromObject(userList));
37//        结果:list转为json数组[{"age":18,"id":0,"password":"123","userName":"jack"},{"age":20,"id":0,"password":"456","userName":"tom"}]
38//        System.out.println("list转为json字符串"+ JSONObject.fromObject(userList).toString()); //不能转为json字符串
39
40//        list<Map<String,Object>> 转json
41        List<Map<String, Object>> mapList = new ArrayList();
42        Map<String, Object> m1 = new HashMap<String, Object>();
43        m1.put("jack", jack);
44        m1.put("tom", tom);
45        Map<String, Object> m2 = new HashMap<String, Object>();
46        m2.put("alex", new User("789", "alex", 20));
47        mapList.add(m1);
48        mapList.add(m2);
49        System.out.println("map转json数组" + JSONArray.fromObject(m2));
50//        转换结果:[{"alex":{"age":20,"id":0,"password":"789","userName":"alex"}}]
51        System.out.println("map转json字符串" + JSONObject.fromObject(m2));
52//结果:{"alex":{"age":20,"id":0,"password":"789","userName":"alex"}}
53        System.out.println(" list<Map<String,Object>> 转json数组" + JSONArray.fromObject(mapList));
54// 结果:[{"tom":{"age":20,"id":0,"password":"456","userName":"tom"},"jack":{"age":18,"id":0,"password":"123","userName":"jack"}},{"alex":{"age":20,"id":0,"password":"789","userName":"alex"}}] 55//        System.out.println(" list<Map<String,Object>> 转json字符串"+JSONObject.fromObject(mapList));//不能转,'object' is an array. Use JSONArray instead
56
57/**
58        * json字符串转map
59*/
60/*  String jsonStr = "{\"alex\":{\"age\":20,\"id\":0,\"password\":\"789\",\"userName\":\"alex\"}}";
61        Map<String,Object> map = jsonToMap(JSONObject.fromObject(jsonStr).get("alex").toString());
62        System.out.println("json字符串转map:"+("age"));*/
63//        {"total":2,"items":[{"age":15,"id":1,"name":"jack"},{"age":16,"id":2,"name":"tom"}]}
64        String jsonStr2 = "{\"total\":2,\"items\":[{\"age\":15,\"id\":1,\"userName\":\"jack\"},{\"age\":16,\"id\":2,\"userName\":\"tom\"}]}";
65        Map<String, Object> stringObjectMap = jsonToMap(jsonStr2);
66for (Map.Entry<String, Object> entry : Set()) {
67            System.out.Key() + "--" + Value());
68        }
69/**输出结果:
70        * total--2
71        items--[{"age":15,"id":1,"userName":"jack"},{"age":16,"id":2,"userName":"tom"}]
72*/
73
74//        jsonstr转list,list中存放Java Bean
75        String jsonStr3 = JSONObject.fromObject(jsonStr2).get("items").toString();
76        System.out.println("jsonStr3=" + jsonStr3);
77        List list = jsonStr2ObjectList(jsonStr3, User.class);
78for (Object u : list) {
79            System.out.println(u);
80        }
81/**
82        * 输出User{id=1, password='null', userName='jack', age=15}
83        User{id=2, password='null', userName='tom', age=16}
84*/
85
86    }
87
88/**
89    * json字符串转map 90    *
91    * @param jsonStr
92    * @return
93*/
94public static Map<String, Object> jsonToMap(String jsonStr) {
95        JSONObject jsonObject = JSONObject.fromObject(jsonStr); //⾸先转换为 JSONObject
96        Iterator<String> nameItr = jsonObject.keys();//获取jsonObject的keySet()的迭代器
97        String key;//接收key值
98        Map<String, Object> outMap = new HashMap<>(); //存放转换结果
99while (nameItr.hasNext()) {
100            key = ();
101            outMap.put(key, (key));
102        }
103return outMap;
104    }
105
106/**
107    * JSONObject类中keys()⽅法默认返回jsonObject的keyset的迭代器
108    * public Iterator keys() {
109    * this.verifyIsNull();
110    * return this.keySet().iterator();
111    * }
112*/
113
114/** json转list,list中存放JavaBean
115    * @param jsonStr 要转换的json字符串
116    * @param clazz  javaBean的Class对象
117    * @return
118*/
119public static List jsonStr2ObjectList(String jsonStr, Class clazz) {
120        JSONArray array = JSONArray.fromObject(jsonStr);
121        List list = new ArrayList();
122for (Iterator itr = array.iterator(); itr.hasNext(); ) {
123            JSONObject jsonObject = (JSONObject) ();
124//取出json字符串中的⼀个⼦字符串,转换为指定类型的JavaBean
125            Object bean = Bean(jsonObject, clazz);
126            list.add(bean);
127        }
128return list;
129    }
130 }
结果:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。