简体   繁体   中英

parsing Json result using Gson

I am using GSON for the first time and when I call httpGet request it returns a Json object string result as so:

{"ContentEncoding":null,"ContentType":null,"Data":[{"Id":3,"Name":"Alabama"},
{"Id":4,"Name":"Alaska"},{"Id":5,"Name":"Arizona"},{"Id":6,"Name":"Arkansas"}]}

All I want is the Data object so my CustomModel class is like so:

 public class CustomModel {

@SerializedName("Id")
private int Id;

@SerializedName("Name")
private string Name;

public int getId() {
   return this.Id;
}
 public void setId(int id) {
   this.Id = id;
}
 public string getName() {
   return this.Name;
}
 public void setName(string Name) {
   this.Name = Name;
}

}

using GSON I try to parse it like this:

 JsonArray Jarray = (JsonArray) parser.parse(results).getAsJsonObject().get("Data");
 for(JsonElement obj : Jarray )
 {

    CustomModel cse = gson.fromJson(obj  , CustomModel.class);
    // list.add(cse); //add the values to global List object
 }

but this throws an error inside the for loop "Expected Begin_Object but was string" . I have been trying to figure this out from googling but no answer helps

I think you aren't importing java.lang.String in CustomModel but are using a custom class named string . This is what Gson is treating as an Object .

Expected Begin_Object but was string

You should be importing java.lang.String .


Yes, instead of looping you could directly deserialize the list as

Type listType = new TypeToken<List<CustomModel>>(){}.getType();
List<CustomModel> listCSE = gson.fromJson(Jarray, listType);

System.out.println(listCSE.get(0).getName()); // Alabama

I think the GSON Documentation might contain your answer.

See https://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Collection-with-Objects-of-Arbitrary-Types .

Here is an example:

package com.stackexchange.stackoverflow;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.annotations.SerializedName;

public class Question19282481 {
  public static void main(String[] args) {
    String json = "{\"ContentEncoding\":null,\"ContentType\":null,\"Data\":[{\"Id\":3,\"Name\":\"Alabama\"},\n" +
      "{\"Id\":4,\"Name\":\"Alaska\"},{\"Id\":5,\"Name\":\"Arizona\"},{\"Id\":6,\"Name\":\"Arkansas\"}]}";

    Gson gson = new Gson();

    JsonParser jsonParser = new JsonParser();
    JsonElement jsonElement = jsonParser.parse(json);
    JsonObject jsonObject = jsonElement.getAsJsonObject();
    JsonArray jsonArray = jsonObject.getAsJsonArray("Data");
    for(JsonElement obj : jsonArray) {
      CustomModel customModel = gson.fromJson(obj, CustomModel.class);
      System.out.println(customModel);
    }
  }

  class CustomModel {
    @SerializedName("Id")
    private int id;

    @SerializedName("Name")
    private String name;

    int getId() {
      return id;
    }

    void setId(int id) {
      this.id = id;
    }

    String getName() {
      return name;
    }

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

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

Which depends on:

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.2.4</version>
</dependency>

The program output is this:

CustomModel{id=3, name='Alabama'}
CustomModel{id=4, name='Alaska'}
CustomModel{id=5, name='Arizona'}
CustomModel{id=6, name='Arkansas'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM