如何通过Gson解析包含JSON数组的JSON对象?

时间:2017-03-21 11:31:36

标签: android json gson

我正在创建一个Android应用,我从网上获得了JSON形式的回复。

JSON文件的结构如下:

{"result": "someresult", "array": [{object1},{object2}]}

目前我正在使用gson.fromJson()方法来解析此JSON,但问题是该数组是JSONArray并且它抛出的异常是JSONObject。 对于结果和数组,我使用@SerializedName注释。 如何使用Gson解析这种JSON? 任何建议将不胜感激。

这是代码:

public class ResultClass {

    @SerializedName("result")
    public String result;

    @SerializedName("array")
    public JSONArray array;

    public static ResultClass getresultFromJSON(String json) {
        try {
            ResultClass resultclass = new Gson().fromJson(json, ResultClass.class);
            return resultclass ;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

4 个答案:

答案 0 :(得分:3)

嗨,如果你的json看起来像这样

{"status": "success",
"data": [
  {
    "trip_id": "5",
    "ride_id": "5",
    "start_location": "8 Rd No 14, Dhaka 1209, Bangladesh",
    "end_location": "Uttara Dhaka, Dhaka Division, Bangladesh",
    "date": "2017-03-14 17:36 PM",
    "time_from": "1489491394079.5322 ",
    "time_to": "1489493194079.5322 ",
    "status": 5,
    "trip_earn": "",
    "currency": "CAD"

  },
{
        "trip_id": "5",
        "ride_id": "5",
        "start_location": "8 Rd No 14, Dhaka 1209, Bangladesh",
        "end_location": "Uttara Dhaka, Dhaka Division, Bangladesh",
        "date": "2017-03-14 17:36 PM",
        "time_from": "1489491394079.5322 ",
        "time_to": "1489493194079.5322 ",
        "status": 5,
        "trip_earn": "",
        "currency": "CAD"

      }
]
}

然后你写一个这样的类来分析数据

public class Example {

@SerializedName("status")
@Expose
private String status;
@SerializedName("data")
@Expose
private List<Datum> data = null;

public String getStatus() {
return status;
}

public void setStatus(String status) {
this.status = status;
}

public List<Datum> getData() {
return data;
}

public void setData(List<Datum> data) {
this.data = data;
}

}

public class Datum {

@SerializedName("trip_id")
@Expose
private String tripId;
@SerializedName("ride_id")
@Expose
private String rideId;
@SerializedName("start_location")
@Expose
private String startLocation;
@SerializedName("end_location")
@Expose
private String endLocation;
@SerializedName("date")
@Expose
private String date;
@SerializedName("time_from")
@Expose
private String timeFrom;
@SerializedName("time_to")
@Expose
private String timeTo;
@SerializedName("status")
@Expose
private Integer status;
@SerializedName("trip_earn")
@Expose
private String tripEarn;
@SerializedName("currency")
@Expose
private String currency;

public String getTripId() {
return tripId;
}

public void setTripId(String tripId) {
this.tripId = tripId;
}

public String getRideId() {
return rideId;
}

public void setRideId(String rideId) {
this.rideId = rideId;
}

public String getStartLocation() {
return startLocation;
}

public void setStartLocation(String startLocation) {
this.startLocation = startLocation;
}

public String getEndLocation() {
return endLocation;
}

public void setEndLocation(String endLocation) {
this.endLocation = endLocation;
}

public String getDate() {
return date;
}

public void setDate(String date) {
this.date = date;
}

public String getTimeFrom() {
return timeFrom;
}

public void setTimeFrom(String timeFrom) {
this.timeFrom = timeFrom;
}

public String getTimeTo() {
return timeTo;
}

public void setTimeTo(String timeTo) {
this.timeTo = timeTo;
}

public Integer getStatus() {
return status;
}

public void setStatus(Integer status) {
this.status = status;
}

public String getTripEarn() {
return tripEarn;
}

public void setTripEarn(String tripEarn) {
this.tripEarn = tripEarn;
}

public String getCurrency() {
return currency;
}

public void setCurrency(String currency) {
this.currency = currency;
}

}

使用

Gson gson = new Gson();
String jsonInString = "{\"userId\":\"1\",\"userName\":\"chayon\"}";
Example user= gson.fromJson(jsonInString, Example.class);
user.getdata().get(position)

答案 1 :(得分:1)

使用jsonschema2pojo创建响应POJO类。

build.gradle

中添加GSON相关性
dependencies {
  compile 'com.google.code.gson:gson:2.8.0'
}

将您的json转换为特定的pojo课程,如下所示:

Gson gson = new GsonBuilder().create();
        Response response = gson.fromJson(response, Response.class);

谢谢!

答案 2 :(得分:1)

只需创建具有结构的类:

class ResultClass {
 String result;
 ArrayData[] array;
}

class ArrayData {
  String field1;
  String field2;
}

之后只使用fromJson方法:

Gson gson = new GsonBuilder().create();
ResultClass resultClass = gson.fromJson(jsonString, ResultClass.class)

答案 3 :(得分:1)

错字...您因为Gson实例没有被告知如何处理JSONArray而导致异常?(我相信,它的完全限定名称是{ {1}}),而Gson等价物为org.json.JSONArray。因此,以下映射不会失败:

com.google.gson.JsonArray

请注意,您在两次混合两个不同的库时已经烧毁,现在在描述您获得的异常时:Gson不会报告@SerializedName("array") public JsonArray array; 或类似的任何内容(它只是没有有关该类型的任何线索),但它报告JSONObject标记(BEGIN_OBJECT)的内部表示类型,因为JSON对象是默认的未知非基本类型,除了基元和数组。

{

同时考虑使用Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 33 path $.array at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:224) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:129) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:220) at com.google.gson.Gson.fromJson(Gson.java:887) at com.google.gson.Gson.fromJson(Gson.java:852) at com.google.gson.Gson.fromJson(Gson.java:801) at com.google.gson.Gson.fromJson(Gson.java:773) ... Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 33 path $.array at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:385) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:213) ... 12 more 与您正在尝试解析的应用数据类(请参阅Demo of Bootstrap 3 centering methods&#39; s {{ 3}})。在这些类中使用与JSON相关的东西通常标记代码气味:某些字段是&#34;真正的Java&#34;,某些字段是&#34;仅JSON&#34;。例如,您可以定义另一个嵌套对象映射类,并告诉Gson它必须是封闭类JsonArray中的JSON数组,例如:

ResultClass

@SerializedName("array")
public List<YourElementClass> array;

拼写错误会影响很多。