欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java Gson解析Json

程序员文章站 2024-03-16 08:38:58
...
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.testng.collections.Lists;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

/**
 * JSON解析
 */
public class JsonToObject {

    public static void main(String[] args) {
//        //单条无嵌套的JSON数据,JSON的key对应对象属性就可以直接绑定值
//        String jsonData = "{'name':'John', 'age':20}";
//        TestPersonT personT = GsonUtil.parseJsonWithGson(jsonData, TestPersonT.class);
//        System.out.println(personT);
//
//        //单条有嵌套的JSON解析
//        String jsonData2 = "{\"name\":\"John\", \"age\":20,\"grade\":{\"course\":\"English\",\"score\":100,\"level\":\"A\"}}";
//        TestPersonT personT2 = GsonUtil.parseJsonWithGson(jsonData2, TestPersonT.class);
//        System.out.println(personT2);

        //多条嵌套JSON解析
        System.out.println("--------------------------------json字符串");
        String jsonData3 = "[{'name':'John', 'grade':[{'course':'English','score':100},{'course':'Math','score':78}]},{'name':'Tom', 'grade':[{'course':'English','score':86},{'course':'Math','score':90}]}]";
        System.out.println(jsonData3);
        System.out.println("--------------------------------list数组");
        ArrayList<TestPersonT> arrayList = GsonUtil.parseJsonArrayWithGson(jsonData3, TestPersonT.class);
        System.out.println(arrayList);
        arrayList.forEach(a->System.out.println(a.getName()));
        List<TestPersonT> list = GsonUtil.jsonToArrayList(jsonData3, TestPersonT.class);
        System.out.println(list);

    }
}

class TestPersonT {
    Integer     age;
    String      name;
    List<Grade> grade;

    public class Grade {
        String course;
        String score;
        String level;

        public String getCourse() {
            return course;
        }

        public void setCourse(String course) {
            this.course = course;
        }

        public String getScore() {
            return score;
        }

        public void setScore(String score) {
            this.score = score;
        }

        public String getLevel() {
            return level;
        }

        public void setLevel(String level) {
            this.level = level;
        }

        @Override
        public String toString() {
            return "Grade [course=" + course + ", score=" + score + ", level=" + level + "]";
        }

    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Grade> getGrade() {
        return grade;
    }

    public void setGrade(List<Grade> grade) {
        this.grade = grade;
    }

    @Override
    public String toString() {
        return "TestPersonT [age=" + age + ", name=" + name + ", grade=" + grade + "]";
    }


}

class GsonUtil{
    //JSON字符串转JavaBean
    public static <T> T parseJsonWithGson(String json,Class<T> type) {
        Gson gson = new Gson();
        return gson.fromJson(json, type);
    }


    //JSON数组转List数组
    public static <T> ArrayList<T> parseJsonArrayWithGson(String json, Class<T> type) {
        Gson gson = new Gson();
        ArrayList<JsonObject> arrayList = gson.fromJson(json, new TypeToken<ArrayList<JsonObject>>(){}.getType());
        List<T> list = Lists.newArrayList();
        arrayList.forEach(a -> list.add(gson.fromJson(a, type)));
        return (ArrayList<T>) list;
    }

    //JSON数组转List数组
    public static <T> ArrayList<T> jsonToArrayList(String json, Class<T> clazz) {
        Type type = new TypeToken<ArrayList<JsonObject>>() {}.getType();
        ArrayList<JsonObject> jsonObjects = new Gson().fromJson(json, type);
        ArrayList<T> arrayList = new ArrayList<T>();
        for (JsonObject jsonObject : jsonObjects) {
            arrayList.add(new Gson().fromJson(jsonObject, clazz));
        }
        return arrayList;
    }


}