0

I have a model:

public class ItemsSet {

@SerializedName("trk")
private String mTracking;
@SerializedName("pg")
private int mPage;
@SerializedName("more")
private boolean mMoreResults;
@SerializedName("items")
private List<Item> mItems;

// I want to annotate this directly without eds object
private List<ItemSubmitter> mItemSubmitters;

...
}

And JSON:

"payload" : {
"trk" : "...",
"##type" : "PaginatedResponse`3",
"eds" : {
  "##type" : "Activity.ExtendedDataSet",
  "usrs" : [
    {
      "##type" : "SNIP",
      "kind" : "connection",
      "identifier" : "4033",
      "name" : "James Johnson"
    },
    {
      "##type" : "SNIP",
      "kind" : "dealercontact",
      "identifier" : "317564",
      "name" : "Savannah Roberts"
    },
    {
      "##type" : "SNIP",
      "kind" : "lsp",
      "identifier" : "89236",
      "name" : "Jenny"
    }
  ]
},
"items" : [..]
... end of json}

I'm using Retrofit with GSON and want to get usrs filed inside eds objetc without serialization this eds object. Can I do it directly? I know in iOS I can do like this "eds.usrs" but here it doesn't work.

Olexii Muraviov
  • 1,456
  • 1
  • 12
  • 36

1 Answers1

1

You need to implement your own JsonDeserializer to solve your issue. See example here: How do I write a custom JSON deserializer for Gson?

My example: https://gist.github.com/alejandro-pnz/8706d672a7640875275163ef3682ef13

And use your own serializer you can make this way:

Gson gson = new GsonBuilder()
                        .registerTypeAdapter(CommentsResponse.class, new CommentsDeserializer())
                        .create();
Community
  • 1
  • 1
Alex
  • 617
  • 4
  • 15
  • I was googling a lot and still can't find any information about custom deserializer for part of json. If I want to write custom deserializer so I need to write it for every model I have or I can write for just one of them and the rest models will be deserialized by default GsonDeserializer? – Olexii Muraviov May 25 '16 at 11:41
  • You can write it for only needed model. I can give your example from one of my own apps: https://gist.github.com/alejandro-pnz/8706d672a7640875275163ef3682ef13 – Alex May 25 '16 at 11:55
  • Thanks! If I put this deserializer into Retrofit client object so only one model will be deserialized with it and other models will be deserialized by default GSON, right? @Alexander – Olexii Muraviov May 25 '16 at 11:58
  • @OlexiiMuraviov, yes, right. Gson gson = new GsonBuilder() .registerTypeAdapter(CommentsResponse.class, new CommentsDeserializer()) .create(); – Alex May 25 '16 at 12:00