简体   繁体   中英

Parsing json by using Gson.fromJson() method into class< T > model is not working

My problem is, I can't parse json by using Gson.fromJson() method into class< T > model.

In my PageOutput.java

public class PageOutput<T> {

      @SerializedName("TotalItemCount")
      public int totalItemCount;

      @SerializedName("Items")
      private T[] items;

      public final T[] getItems() {
          return items;
      }
}

In Property.java

public class Property {
   @SerializedName("Id")
   public String id;

   @SerializedName("Title")
   public String title;

   @SerializedName("Price")
   public BigDecimal price;
    ....
}

In Main.java ,

PageOutput<Property>  output = new Gson.fromJson(jsonString, new TypeToken<PageOutput<Property>>(){}.getType());

When project is compiled, I get null in Items.

But when I use

PageOutput<Property>  output = new Gson.fromJson(jsonString, PageOutput.class);

I will get the result in generic object type for T[] items, by the meantime I should get Property type. (Line 18)

output = {com.myapp.PageOutput@830048974608}
items = {java.lang.Object[17]@830048616120} //Line 18
[0] = {com.google.gson.internal.LinkedTreeMap@830048777632} size = 16
[1] = {com.google.gson.internal.LinkedTreeMap$Node@830047149712}"Id" -> "2936918.0"
[2] = {com.google.gson.internal.LinkedTreeMap$Node@830047452528}"Title" -> "Valdor, Penang"
[3] = {com.google.gson.internal.LinkedTreeMap$Node@830047985896}"Price" -> "7.5698E9"

And when I cast this object,

Property[] properties = output.getItems(); //Return error

I will get error:

java.lang.ClassCastException: java.lang.Object[] cannot be cast to com.myapp.model.Property[]

How can I solve the problem? Please help and thank you very much.

This is the right way to parse it

PageOutput<Property>  output = new Gson.fromJson(jsonString, new TypeToken<PageOutput<Property>>(){}.getType());

and getting null at items means that you need to check your json string and how it was built

Try this -

items= output.getItems();

Property[] properties = itmes.toArray(new Property[items.size()]);

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