通过使用Gson.fromJson()方法将json解析为类模型是行不通的

我的问题是,我不能通过使用Gson.fromJson()方法解析json到class 模型。

在我的PageOutput.java中

public class PageOutput { @SerializedName("TotalItemCount") public int totalItemCount; @SerializedName("Items") private T[] items; public final T[] getItems() { return items; } } 

Property.java中

 public class Property { @SerializedName("Id") public String id; @SerializedName("Title") public String title; @SerializedName("Price") public BigDecimal price; .... } 

Main.java中

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

编译项目时,我在Items中得到null。

但是当我使用时

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

我会得到T []项的通用对象类型的结果,同时我应该得到Property类型。 (第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" 

当我投射这个物体时,

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

我会得到错误:

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

我该如何解决这个问题? 请帮助,非常感谢。

这是解析它的正确方法

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

并且在项目处获取null意味着您需要检查您的json字符串以及它是如何构建的

尝试这个 –

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