浅谈JSONObject,GSON解析JSON

这次大致梳理一下关于JSON的其中两种解析方法:JSONObject和GSON

 

例:

 待解析的Class.json文件

 

[ { "id" : "1" , "name" : "Qbin" , "sex" : "male" },

  { "id" : "2" , "name" : "Qmm" , "sex" : "female" },

  { "id" : "3" , "name" : "cmy" , "sex" : "male" }]

 

 

JSONObject解析:

public class Main{

  .....

  parseJSONWithJSONObject(jsondata);

  .....

 

  private void parseJSONWithJSONObject(String jsonData){

    try{

      JSONArray jsonArray = new JSONArray(jsondata);

      //由于jsondata文件中定义了json数组

      for(int i = 0; i <jsonArray.length(); i++){

        JSONObject jsonObject = jsonArray.getJSONObject(i);

 

        //每个jsonObject对象中包含id , name , sex

        String id = jsonObject.getString("id");

        String name = jsonObject.getString("name");

        String sex = jsonObject.getString("sex");

                

        Log.d( "JSONObject" , "id =" + id);

        Log.d( "JSONObject" , "name=" + name);

        Log.d( "JSONObject" , "sex=" + sex);

      }

    }catch(Exception e){

      e.printStackTrace();

    }

  }

}

 

 

 

GSON解析:

首先添加GSON依赖:

compile 'com.google.code.gson:gson:2.7'

 

然后创建与Json对应的类

public class Student{

  private String id;

  private String name;

  private String sex;

 

  public void setId(String id){

    this.id = id;

  }

  public String getId(){

    return id;

  }

 

  public void setName(String name){

    this.name = name;

  }

  public String getName(){

    return name;

  }

 

  public void setSex(String sex){

    this.sex = sex;

  }

  public String getSex(){

    return sex;

  }

}

 

public class Main{

  .......

  parseJSONWithGSON(jsondata);

  .......

  private void parseJSONWithGSON(String jsondata){

    Gson gson = new Gson();

    List<Student> studentList = gson.fromJson(jsondata , new TypeToken<List<Student>>(){}.getType());

    //TypeToken类帮助捕获泛型信息,然后存入匿名内部类中,通过getType()方法获取类型

    for(Student student : studentList){ 

      Log.d( "JSONObject" , "id =" + student.getId());

      Log.d( "JSONObject" , "name=" + student.getName());

      Log.d( "JSONObject" , "sex=" + student.getSex());

    }

  }

}

 

 

posted @ 2018-02-06 18:38  clicli  阅读(286)  评论(0编辑  收藏  举报