JAVA中的四种JSON解析方式详解

JAVA中的四种JSON解析方式详解

我们在日常开发中少不了和JSON数据打交道,那么我们来看看JAVA中常用的JSON解析方式。
1、JSON官方 脱离框架使用
2、GSON
3、FastJSON 有问题
4、jackson 常用
JSON操作涉及到的类:

public class Student {

    private int id;
    private String name;
    private int age;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Student(int id, String name, int age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }
    public Student() {
        super();
    }
    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
    }
}

public class Grade {

    private int id;
    private String name;
    private ArrayList<Student> stus;
    public Grade(int id, String name, ArrayList<Student> stus) {
        super();
        this.id = id;
        this.name = name;
        this.stus = stus;
    }
    public Grade() {
        super();
    }
    @Override
    public String toString() {
        return "Grade [id=" + id + ", name=" + name + ", stus=" + stus + "]";
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public ArrayList<Student> getStus() {
        return stus;
    }
    public void setStus(ArrayList<Student> stus) {
        this.stus = stus;
    }

}

JSON官方的解析最具有通用性,但是有点小麻烦。

package cn.itcast.test;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.junit.Test;

import java.util.ArrayList;

public class JsonTest {
    @Test
    public void test1() {
        String json1 = "{'id':1,'name':'JAVAEE-1703','stus':[{'id':101,'name':'刘一','age':16},{'id':102,'name':'刘二','age':23}]}";
        //数组
        String json2 = "['北京','天津','杭州']";
//        JSONObject jObject = new JSONObject(json1);

        JSONObject jsonObject = JSONObject.fromObject(json1);
//        System.out.println(jsonObject);
//        Map<String,Object> map = jsonObject;
//        for (Map.Entry<String, Object> entry : map.entrySet()) {
//            System.out.println(entry.getKey());
//            System.out.println(entry.getValue());
//            System.out.println("=========");
//        }



        Grade grade = new Grade();
        grade.setId(jsonObject.getInt("id"));
        grade.setName(jsonObject.getString("name"));
        ArrayList<Student> students = new ArrayList<>();
        grade.setStus(students);

        JSONArray stus = jsonObject.getJSONArray("stus");
        for (Object o : stus) {
//            System.out.println(o);
            JSONObject jsonObject1 = JSONObject.fromObject(o);
            Student student = new Student(jsonObject1.getInt("id"), jsonObject1.getString("name"), jsonObject1.getInt("age"));
            grade.getStus().add(student);
        }

        System.out.println(grade);

    }
    @Test
    public void test2(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", 100);
        jsonObject.put("name", "二弟");
        jsonObject.put("age", 30);

        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("id", 102);
        jsonObject1.put("name", "狗蛋");
        jsonObject1.put("age", 10);

        JSONArray jsonArray = new JSONArray();
        jsonArray.add(jsonObject);
        jsonArray.add(jsonObject1);
        System.out.println(jsonArray);


    }
}

GSON解析是谷歌的,也比较好用


public class GSONTest {

    //解析
    @Test
    public void test1() {
        // 对象嵌套数组嵌套对象
        String json1 = "{'id':1,'name':'JAVAEE-1703','stus':[{'id':101,'name':'刘一','age':16}]}";
        // 数组
        String json2 = "['北京','天津','杭州']";

        Gson gson=new Gson();
        //1、
        //解析对象:第一个参数:待解析的字符串 第二个参数结果数据类型的Class对象
        Grade grade=gson.fromJson(json1, Grade.class);
        System.out.println(grade);

        //2、
        //解析数组要求使用Type
        ArrayList<String> list=gson.fromJson(json2, 
                new TypeToken<ArrayList<String>>(){}.getType());
        System.out.println(list);
    }
    //生成
    @Test
    public void test2(){
        ArrayList<Student> list=new ArrayList<>();
        for(int i=1;i<3;i++){
            list.add(new Student(101+i, "码子", 20+i));
        }
        Grade grade=new Grade(100001,"张三", list);
        Gson gson=new Gson();
        //将对象转换为诶JSON格式字符串
        String json=gson.toJson(grade);
        System.out.println(json);

    }
}

FastJSON是阿里巴巴的产品,效率最高

public class FASTJson {

    //解析
    @Test
    public void test1() {
        // 对象嵌套数组嵌套对象
        String json1 = "{'id':1,'name':'JAVAEE-1703','stus':[{'id':101,'name':'刘铭','age':16}]}";
        // 数组
        String json2 = "['北京','天津','杭州']";
        //1、
        //静态方法
        Grade grade=JSON.parseObject(json1, Grade.class);
        System.out.println(grade);
        //2、
        List<String> list=JSON.parseArray(json2, String.class);
        System.out.println(list);
    }
    //生成
    @Test
    public void test2(){
        ArrayList<Student> list=new ArrayList<>();
        for(int i=1;i<3;i++){
            list.add(new Student(101+i, "码子", 20+i));
        }
        Grade grade=new Grade(100001,"张三", list);
        String json=JSON.toJSONString(grade);
        System.out.println(json);
    }
}

jackSon解析JSON,SpringMVC内置的解析器就是这个

package cn.itcast.test;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class jackSonTest {
    @Test
    public void test1() throws IOException {
        // 对象嵌套数组嵌套对象
        String json1 = "{\"id\":1,\"name\":\"JAVAEE-1703\",\"stus\":[{\"id\":101,\"name\":\"刘一\",\"age\":16}]}";
        // 数组
        String json2 = "[\"北京\",\"天津\",\"杭州\"]";

        ObjectMapper mapper = new ObjectMapper();
        Grade grade = mapper.readValue(json1, Grade.class);
        System.out.println(grade);

        List<String> list = mapper.readValue(json2, new TypeReference<List<String>>() {
        });
        System.out.println(list);

    }

    @Test
    public void test2() throws JsonProcessingException {
        ArrayList<Student> students = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            students.add(new Student(100 + i, "二稿" + i, 1000 + i));

        }
        Grade grade = new Grade(22, "语文", students);
//        System.out.println(grade);
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(grade);
        System.out.println(s);
    }
}

除了JSON官方的对类没有要求,剩下的都要求是标准的类,否则无法解析,因为都用到了反射。

posted @ 2019-09-23 22:57  道理我都懂Zz  阅读(23999)  评论(0编辑  收藏  举报