java中将Map集合、对象、字符串转换为JSON对象

1、Map集合转JSON对象

创建一个Map集合;
新建json对象,并将Map引入json中。

public void demo1(){ 
    //创建一个Map集合
    Map<String, String> map = new HashMap<>();
    map.put("1729210001","zhangsan");
    map.put("1729210002","lisi");
    map.put("1729210003","wangwu");
    //Map-->json
    JSONObject json = new JSONObject(map);//引入json对象
    System.out.println(json);
    //打印json:{"1729210003":"wangwu","1729210002":"lisi","1729210001":"zhangsan"}
}

2、普通对象转JSON对象

创建一个Person类和Address类(此处省略了有参/无参构造方法、get()方法、set()方法);
新建Person对象和Address对象,并赋值;
新建json对象,并将对象引入json中。

public class Person { 
    private String name;
    private int age;
    private Address address;
}

public class Address { 
    private String homeAddress;
    private String schoolAddress;
}

@Test
public void demo2(){ 
    //创建一个Person对象
    Person per =new Person();
    per.setName("zhangsan");
    per.setAge(23);
    Address add = new Address("杭州","宁波");
    per.setAddress(add);
    //Javabean-->json
    JSONObject json = new JSONObject(per);
    System.out.println(json);
    //打印json:{"address":{"schoolAddress":"宁波","homeAddress":"杭州"},"name":"zhangsan","age":23}
}

3、字符串转JSON对象

字符串类型的需要符合json格式;
将字符串引入到json对象中。

@Test
public void demo3(){ 
    String str = "{\"name\":\"zhangsan\",\"age\":23}";//需要符合json格式
    JSONObject json = new JSONObject(str);
    System.out.println(json);
}