Nick Cardoso Nick Cardoso - 5 months ago 13
JSON Question

How do I use GSON to convert an object array to an array of their IDs

I've been using

Gson.toJson
to convert my object for a request:

class Convertable {

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

}


Which gave me JSON that looks something like this:

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


Now my object has changed to

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
}


But if it's possible I want to do something just as simple. How do I achieve this? Can it be done without writing a custom serializer and having to manually convert everything else in the object?




Edit - More info:

My current approach is as follows, I need to add and expose a method:

class Convertable {

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

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

}


I'd like to know if there is a better way than this

Answer

You don't need a custom converter for the Convertable class, just for the MyChild. And register it using GsonBuilder#registerTypeHierarchyAdapter. That way you don't need to change anything about 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;
  }
}