繁体   English   中英

使用Gson.fromJson()方法将json解析为class <T>模型不起作用

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

我的问题是,我无法通过使用Gson.fromJson()方法将json解析为class <T>模型。

在我的PageOutput.java中

public class PageOutput<T> {

      @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<Property>  output = new Gson.fromJson(jsonString, new TypeToken<PageOutput<Property>>(){}.getType());

编译项目时,Items中为空。

但是当我使用

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

我将获得T []项目的通用对象类型的结果,与此同时,我应该获得属性类型。 (第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<Property>  output = new Gson.fromJson(jsonString, new TypeToken<PageOutput<Property>>(){}.getType());

并在项目中获取null意味着您需要检查json字符串及其构建方式

尝试这个 -

items= output.getItems();

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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