Gson在解析java数据格式的三种范例

       Gson是谷歌提供的一个开源库,用来解析json格式的数据非常好用。如果用maven进行项目管理的话,可以在pom.xml中引入如下依赖:

<dependency>
    <groupId>com.google.code.gsongroupId>
    <artifactId>gsonartifactId>
    <version>2.8.0version>
dependency>

      如果不是,请自行下载jar包:gson-2.8.0.jar。

   接下来讲述如何用Gson进行单条无嵌套Json数据的解析、单条有嵌套的json数据解析和解析json数组:

import com.google.gson.Gson;

public class GJsonExap {
    public static void main(String[] args) {
        /*
        一、单条无嵌套json数据的解析
         */
        //给出如下的json,将如下json数据解析成Person对象

        String gStr = "{'name':'Json','age':20}";
        String gStr1 = "{\"name\":\"Rose\",\"age\":12}";
        Gson gson = new Gson();
        Person person = gson.fromJson(gStr,Person.class);
        Person person1 = gson.fromJson(gStr1,Person.class);
        System.out.println(person.toString());
        System.out.println(person1.toString());
    }
}
class Person{
    private String name;
    private int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    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;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

import com.google.gson.Gson;

public class GsonTest1{
    /*
    考虑到json数据的不同,那么解析Json时候所用的类也可能不同,比如这里
    你可能用Person,而如果解析其他数据时又变成Dog.Cat了,因此考虑
    将Gson解析的步骤封装,并提供泛型参数,示例如下

     */
    public static void main(String[] args) {
      String strJson = "{\"name\":\"wangcai\",\"category\":\"旺旺\"}";
      Dog dog = parseJsonWithGson(strJson,Dog.class);
        System.out.println(dog.toString());
    }
    public static <T> T parseJsonWithGson(String jsonData,Class<T>type){
        Gson gson = new Gson();
       return gson.fromJson(jsonData,type);
    }
}
class Dog{
    private String name;
    private String category;

    public Dog() {
    }

    public Dog(String name, String category) {
        this.name = name;
        this.category = category;
    }

    public String getName() {
        return name;
    }

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

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", category='" + category + '\'' +
                '}';
    }
}
package cn.itcast.scala.generic.java;

public class GsonTest2 {
    /*
    二、单条有嵌套的json数据:{"name":"John","age":"20","grade":{"course":"English","score":"100","level":"A"}}
    此类数据要用公共内部类来解决
     */
    public static void main(String[] args) {
        String strJson = "{\"name\":\"John\",\"age\":20,\"grade\":{\"course\":\"English\",\"score\":100,\"Level\":\"A\"}}";
        String strJson1 = "{'name':'Rose','age':22,'grade':{'course':'English','score':100,'level':'A'}}";
        //用先前GsonTest1中封装的Gson解析工具类,提供泛型参数
        Student stu1 = GsonTest1.parseJsonWithGson(strJson,Student.class);
        Student stu2 = GsonTest1.parseJsonWithGson(strJson1,Student.class);
        System.out.println(stu1.toString());
        System.out.println(stu2.toString());
    }
}
// 一、根据Json数据串定义Student对象
class Student{
     private String name;
     private int age;
     private Grade grade;
        public class Grade{
            private String course;
            private int score;
            private String level;

            public String getCourse() {
                return course;
            }

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

            public int getScore() {
                return score;
            }

            public void setScore(int 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 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 Grade getGrade() {
        return grade;
    }

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

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", grade=" + grade +
                '}';
    }
}

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

package cn.itcast.scala.generic.java;

import java.util.List;

public class GsonTest3 {
    /*
   三、 解析Json数组:比如有如下Json数据:json数组最外层要加“[]”
    [{'name':'John','grade':[{'course':'English','score':100},{'course':'Math','score':78}]},
     {'name':'Tom','grade':[{'course':'English','score':90},{'course':'Math','score':87}]}]
    Student(name,grade[English,Math])
    处理这类数据要用到List
     */
    public static void main(String[] args) {

        String jsonDate = "[{'name':'John', 'grade':[{'course':'English','score':100},{'course':'Math','score':78}]},{'name':'Tom', 'grade':[{'course':'English','score':86},{'course':'Math','score':90}]}]";


        List students =GsonUtil.parsJsonArrayWithGson(jsonDate,Stu.class);
        System.out.println(students);
    }
}
 
  
//下面是我重新写的一个Json工具类
package cn.itcast.scala.generic.java;

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

import java.util.List;

public class GsonUtil {
    //将json对象解析成相应的映射对象
    public static <T> T parseJsonWithGson(String str,Class<T> type){
        Gson gson = new Gson();
        return gson.fromJson(str,type);
    }
    //将json对象解析成相应的映射对象列表
    public static <T> List<T> parsJsonArrayWithGson(String str,Class<T> type){
       Gson gson  = new Gson();
       /*GSON提供了 TypeToken 这个类来帮助我们捕获(capture)像List这样的泛型信息。
       上文创建了一个匿名内部类,这样,Java编译器就会把泛型信息编译到这个匿名内部类里,然后在运行时就可以被
       getType()方法用反射API提取到。
    */
       return gson.fromJson(str,new TypeTokenT>>(){
           }.getType());
    }
}
class Stu{ private String name ; private List grade ; public class Grade{ private String course ; private int score ; public String getCourse() { return course ; } public void setCourse(String course) { this . course = course; } public int getScore() { return score ; } public void setScore( int score) { this . score = score; } @Override public String toString() { return "Grade{" + "course='" + course + ' \' ' + ", score=" + score + '}' ; } } public String getName() { return name ; } public void setName(String name) { this . name = name; } public List getGrade() { return grade ; } public void setGrade(List grade) { this . grade = grade; } @Override public String toString() { return "Student{" + "name='" + name + ' \' ' + ", grade=" + grade + '}' ; }}

你可能感兴趣的:(Java)