Json转换

#阿里巴巴fastJson #

 

创建对象

User user = new User();
user.setGrade("1班");
user.setId(1);
user.setName("zs");

User user2 = new User();
user2.setGrade("2班");
user2.setId(2);
user2.setName("ls");

//新建数组
List list = new ArrayList();
list.add(user);
list.add(user2);

1、 pojo 转 Json 字符串

    String s1 = JSON.toJSONString(user);
    System.out.println(s1);

输出:

{"grade":"1班","id":1,"name":"zs"}

2、 json字符串 转 json 对象

    JSONObject jsonObject = JSONObject.parseObject(s1);
  
    Object id = jsonObject.get("id"); //拿到id
    System.out.println(id);//1
    System.out.println("json对象转json字符串 "+jsonObject.toJSONString());

输出:

json对象转json字符串 {"grade":"1班","name":"zs","id":1}
1

3、 json字符串 转 pojo 对象

 User user1 = JSON.parseObject(s1, User.class);
 System.out.println(user1.getName());

输出:

zs

4、 json字符串 转 list 对象

List users = JSONArray.parseArray(s1, User.class);
users.forEach(obj-> System.out.println(obj.toString()));

输出:

com.alibaba.fastJson.User@762efe5d
com.alibaba.fastJson.User@5d22bbb7

5、 list转json字符串

  Object toJSON = JSON.toJSON(list);
 System.out.println("list-->jsonStr"+toJSON);

输出:

list转json字符串[{"grade":"1班","id":1,"name":"zs"},{"grade":"2班","id":2,"name":"ls"}]

6、 json字符串 转 Map

    String str = "{\"1\":\"zs\",\"2\":\"ls\",\"4\":\" ww\",\"5\":\"ml\"}";
    //第一种
    Map maps = (Map) JSON.parse(str);
    System.out.println("第1种");
    for (Object obj : maps.keySet()) {
        System.out.println("key:" + obj + "value:" + maps.get(obj));
    }

    //第二种
    Map mapTypes = JSON.parseObject(str);
    System.out.println("第2种");
    for (Object obj : mapTypes.keySet()) {
        System.out.println("key:" + obj + "value:" + mapTypes.get(obj));
    }

    //第三种
    Map mapType = JSON.parseObject(str, Map.class);
    System.out.println("第3种");
    for (Object obj : mapType.keySet()) {
        System.out.println("key:" + obj + "value:" + mapTypes.get(obj));
    }

    //第四种
    /**
     * JSONObject是Map接口的一个实现类
     */
    Map json = (Map) JSONObject.parse(str);

    //第五种
    Map jsonMap = (Map) JSONObject.parseObject(str);

输出:

第1种
key:1value:zs
key:2value:ls
key:4value: ww
key:5value:ml
第2种
key:1value:zs
key:2value:ls
key:4value: ww
key:5value:ml
第3种
key:1value:zs
key:2value:ls
key:4value: ww
key:5value:ml

你可能感兴趣的:(常见编程方法)