gson字段具有相同的名称但不同的类型,即对象和数组

时间:2016-09-23 15:47:17

标签: json gson android

我想使用GSON解析下面的json。请指导如何使用GSON实现这一点,因为student字段用作对象以及数组,我应该如何定义我的pojo以及如何解析这种类型的json

{
  "school": [
    {
      "student": {
        "name": "Rose", 
        "address": "some address"
      }, 
      "age": "15", 
      "section": "A"
    }, 
    {
      "student": [
        {
          "name": "David", 
          "address": "Some place"
        }
      ], 
      "age": "14", 
      "section": "B"
    }
  ]
}

Gson gson = new Gson();
JSONArray jsonArray = response.getJSONArray("school");
Type listType = new TypeToken<ArrayList<School>>(){}.getType();
listSchool = gson.fromJson(jsonArray.toString(), listType);
  

获取com.google.gson.JsonSyntaxException:

     

java.lang.IllegalStateException:预期BEGIN_ARRAY但是BEGIN_OBJECT异常

1 个答案:

答案 0 :(得分:0)

您可以使用此服务轻松生成POJO java类:http://www.jsonschema2pojo.org/

对于你的json,它会生成:

-----------------------------------com.example.School.java-----------------------------------

package com.example;

import java.util.ArrayList;    
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("org.jsonschema2pojo")
public class School {

@SerializedName("school")
@Expose
public List<School_> school = new ArrayList<School_>();

}
-----------------------------------com.example.School_.java-----------------------------------

package com.example;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("org.jsonschema2pojo")
public class School_ {

@SerializedName("student")
@Expose
public List<Student> student = new ArrayList<Student>();
@SerializedName("age")
@Expose
public String age;
@SerializedName("section")
@Expose
public String section;

}
-----------------------------------com.example.Student.java-----------------------------------

package com.example;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("org.jsonschema2pojo")
public class Student {

@SerializedName("name")
@Expose
public String name;
@SerializedName("address")
@Expose
public String address;

基本上,您应该为数组中的学生项目和学生对象使用不同的类名。