JSON 与 对象 、集合 之间的转换

1. JSON 格式

对象格式

{"name":"JSON","address":"北京市西城区","age":25}//JSON的对象格式的字符串

对象数组格式

[{"name":"JSON","address":"北京市西城区","age":25},{"name":"JSON","address":"北京市西城区","age":25}]//对象数组

2. java 对象转 JSON 字符串

fastjson

JSONObject.toJSONString(result) // fastjson

json-lib

//1、使用JSONObject
        JSONObject json = JSONObject.fromObject(stu);
          //2、使用JSONArray
        JSONArray array=JSONArray.fromObject(stu);
        
        String strJson=json.toString();
        String strArray=array.toString();

3. JSON字符串转 java对象

json-lib

JSONObject jsonObject=JSONObject.fromObject(objectStr);
        Student stu=(Student)JSONObject.toBean(jsonObject, Student.class);
        
        //2、使用JSONArray
        JSONArray jsonArray=JSONArray.fromObject(arrayStr);
        //获得jsonArray的第一个元素
        Object o=jsonArray.get(0);
        JSONObject jsonObject2=JSONObject.fromObject(o);
        Student stu2=(Student)JSONObject.toBean(jsonObject2, Student.class);

4. list 转 json字符串

json-lib

//1、使用JSONObject
       // JSONObject listObject=JSONObject.fromObject(lists);
        //2、使用JSONArray
        JSONArray listArray=JSONArray.fromObject(lists);

5. json字符串转 list

从上面的例子可以看出list的对象只能转化为数组对象的格式

//转化为list
List<Student> list2=(List<Student>)JSONArray.toList(JSONArray.fromObject(arrayStr), Student.class);

//转化为数组
Student[] ss =(Student[])JSONArray.toArray(JSONArray.fromObject(arrayStr),Student.class);

6. map 转 json字符串

//1、JSONObject
        JSONObject mapObject=JSONObject.fromObject(map);
      
        //2、JSONArray
        JSONArray mapArray=JSONArray.fromObject(map);

7. json字符串转 map

String strObject="{\"first\":{\"address\":\"中国上海\",\"age\":\"23\",\"name\":\"JSON\"}}";
        
        //JSONObject
        JSONObject jsonObject=JSONObject.fromObject(strObject);
        Map map=new HashMap();
        map.put("first", Student.class);

        //使用了toBean方法,需要三个参数 
        MyBean my=(MyBean)JSONObject.toBean(jsonObject, MyBean.class, map);
        System.out.println(my.getFirst());

MyBean

import java.util.Map;

import com.cn.study.day3.Student;

public class MyBean {
    
    private Student first;

    public Student getFirst() {
        return first;
    }

    public void setFirst(Student first) {
        this.first = first;
    }

    

}

使用toBean()方法是传入了三个参数,第一个是JSONObject对象,第二个是MyBean.class,第三个是一个Map对象。通过MyBean可以知道此类中要有一个first的属性,且其类型为Student,要和map中的键和值类型对应,即,first对应键 first类型对应值的类型。

相关推荐