0

I faced a problem with json serialization with Gson. So, I access an API using retrofit with dynamic returns as there's inconsistently json field.

The return looks like this:

{
        "_id": "5959bace87b42b0012dd32e3",
        "user": {
            "_id": "58fdaca91ab5920012328669",
            "email": "xxx@xxxx.xx",
            "fullName": "User full name"
            "phonenumber": "+449xxxx",
            "profilePicture": ""
        }
     }

But sometimes, the return would be like this (look at user field):

{
            "_id": "5959bace87b42b0012dd32e3", 
            "user": "58fdaca91ab5920012328669"
}

This is my POJO

public class Order{

   @PrimaryKey
   @SerializedName("_id")
   @Expose
   String id;

   @SerializedName("user")
   @Expose
   User user;
   //getter setter
}

Anyone know how to solve this problem?

Thanks

Community
  • 1
  • 1
ikhsanudinhakim
  • 1,554
  • 16
  • 23
  • I'm posting this as a comment because I'm not sure it's the best approach. I had a similar case and made ``user`` a ``JsonElement``. Gson is able to parse the json string into this type. The problem is that then you have to manually check what user is and convert it to the proper object. – Fred Jul 03 '17 at 08:22
  • what is your User POJO? – matrix Jul 03 '17 at 08:22

1 Answers1

0

I don't know its working or not, just give it a try :

public class Order{

   @PrimaryKey
   @SerializedName("_id")
   @Expose
   String id;

   @SerializedName("user")
   @Expose
   User user;

   @SerializedName("user")
   @Expose
   String userString;
   //getter setter
}

Check for null and use which one is available.

EDIT : check this, this also

SANAT
  • 8,489
  • 55
  • 66
  • 1
    i think there will be a crash, and it may look random, as the behavior of deserialization may differ each time, and the json itself is not the same always, so when it occurs and json user is string, and parser try to deserialize into User object the crash (exception) ma occur **though it worth a try, i like ur idea** – Yazan Jul 03 '17 at 09:12