【问题标题】:How do I use GSON to convert an object array to an array of their IDs如何使用 GSON 将对象数组转换为其 ID 数组
【发布时间】:2016-04-21 10:27:20
【问题描述】:

我一直在使用Gson.toJson 将我的对象转换为请求:

class Convertable {

    private String[] mApples;
    private String[] mOranges;
    ...

}

这给了我看起来像这样的 JSON:

{
    "apples": [
        "ahadhahajjajajaj",
        "afwqrbvlnwegoihw",
        "bnobnwoibbwwrbwb"
    ],
    "oranges": [
        "ahadhaha",
        "abvlnwew",
        "bnobrbwb"
    ],
    ...
}

现在我的对象已经变成了

class Convertable {

    private String[] mApples;
    private MyChild[] mOranges;
    ...
}

class MyChild {

    private String mId; //is the string the json contained before
    ... //contains other fields the request doesnt need
}

但如果可能的话,我想做一些同样简单的事情。我如何实现这一目标?是否可以在不编写自定义序列化程序且不必手动转换对象中的所有其他内容的情况下完成?


编辑 - 更多信息:

我目前的做法如下,我需要添加和暴露一个方法:

class Convertable {

    private String[] mApples;
    private transient MyChild[] mOranges;
    ...

    @SerializedName("oranges")
    public String[] getMyChildIds() {
        ...
    }

}

我想知道是否有比这更好的方法

【问题讨论】:

  • 把你的 MyChild 类放到 Convertable 中,并制作 ArrayList 而不是 MyChild 的 Array,然后尝试通过 Gson 将其转换为 json。但它也应该由 Array 完成,但我使用了 ArrayList 并且它已经转换了。

标签: android json gson


【解决方案1】:

Convertable 类不需要自定义转换器,MyChild 只需要。并使用GsonBuilder#registerTypeHierarchyAdapter 注册它。这样您就无需更改任何关于 Convertable 的内容。

public class MyChildAdapter extends TypeAdapter<MyChild> {
  @Override
  public void write(JsonWriter out, MyChild myChild)
          throws IOException
  {
    out.value(myChild.getId());
  }

  @Override
  public MyChild read(JsonReader in) throws IOException {
    // implement it if needed
    return null;
  }
}

【讨论】:

    猜你喜欢
    • 2016-05-07
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2019-01-04
    • 2014-11-07
    • 2012-02-29
    • 2017-12-24
    相关资源
    最近更新 更多