1

I have this JSON :

{
    "attributes": {
        "date": "2016-01-01"
    },
    "first": "05:33",
    "second": "05:50",
    "third": "07:22"
}

Usually we do something like this to parse this json using Gson retrofit parser :

Class MyObject {
    @SerializedName("attributes")
    Attribues attributes;
    @SerializedName("first")
    String first;
    @SerializedName("second")
    String second;
    @SerializedName("third")
    String third;
}

And

Class Attributes {
    @SerializedName("date")
    String date;
}

But what I want to do is this:

Class MyObject {
    // I want date to be here and ignoring the attributes key <--- 
    String date;
    @SerializedName("first")
    String first;
    @SerializedName("second")
    String second;
    @SerializedName("third")
    String third;
}

How can we do this ?

MBH
  • 16,271
  • 19
  • 99
  • 149
  • I think you should do custom converter. Take a look on this answer - http://stackoverflow.com/questions/35502079/custom-converter-for-retrofit-2 – Divers Aug 03 '16 at 21:00
  • but i use a library for android called retrofit and they use their converter, if it can be possible in a way that i use their converter and make it as for second solution. – MBH Aug 03 '16 at 21:03
  • 1
    Yes, link which I gave you is exactly about retrofit2 custom json converter – Divers Aug 03 '16 at 21:13

1 Answers1

2

90% of questions about GSon has the same answer: use a custom TypeAdapter

Daniele Segato
  • 12,314
  • 6
  • 62
  • 88
  • So, if my class has 10+ fields and only one field is problematic, I cannot just tell GSon how to convert that specific field, but have to write an entire custom adapter for my class? My class has a Time field whose type is `DateTime` in C# but `Date` in Java. Newtonsoft.Json serialised it like '2016-11-05T14:23:00', but GSon throwed an exception (No time zone indicator) for that field while deserialising the object. – Damn Vegetables Nov 06 '16 at 08:11
  • just provide your type adapter for a Date – Daniele Segato Nov 06 '16 at 10:00