【发布时间】: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 并且它已经转换了。