如何使用GSON将对象数组转换为其ID数组

时间:2016-04-21 10:27:20

标签: android json gson

我一直在使用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() {
        ...
    }

}

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

1 个答案:

答案 0 :(得分: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;
  }
}