【问题标题】:Parse Json with GSON to ObservableField使用 GSON 将 Json 解析为 ObservableField
【发布时间】:2016-11-16 18:55:00
【问题描述】:

我尝试使用 GSON 将 JSON 结果解析为我的 POJO 类。

当我的 POJO 看起来像

public class Content {
    public String name;
    public String shortDescription;
}

我可以成功地做到这一点,将我的 Json 数据放在 c1.name 和 c1.shortDescription 中:

GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();

Content c1 = gson.fromJson(contentSt, Content.class);

但是当我的 POJO 看起来像

public class Content {
    public ObservableField<String> name= new ObservableField<String>();
    public ObservableField<String> shortDescription = new ObservableField<String>(); 
}

我收到了这个错误

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 151 path $.shortDescription

任何建议如何解决这个问题?我很高兴得到任何帮助,并感谢您阅读我的问题。

【问题讨论】:

    标签: android gson pojo android-databinding


    【解决方案1】:

    你现在最好使用 POJO 并从 BaseObservable 扩展。这是实现双向数据绑定的另一种方法。参考:Data Binding Library

    【讨论】:

      【解决方案2】:

      您在 GSON 中尝试过TypeAdapter 吗? 您可以将字段值从对象转换为 JSON 格式,例如:

      val gsonBuilder = GsonBuilder()
      gsonBuilder.setTypeAdapter(Any::class, object : TypeAdapter<*>() {
          ...
          override fun write(`in`: Any, `out`: JSONWriter) {
              // your transform code here, for example:
              if (`in`.observableFieldItem is ModelHasObservableFields) {
                  `out`.observableFieldItem = `in`.observableFieldItem.get()
              }
          }
          ...
      })
      

      以上是示例,请记住,可能语法不正确,但您可以参考此链接:http://www.javacreed.com/gson-typeadapter-example/ 希望对您有所帮助!

      【讨论】:

        猜你喜欢
        • 2013-02-02
        • 2011-04-26
        • 1970-01-01
        • 2013-09-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-12
        相关资源
        最近更新 更多