I'm using GSON
to create a SugarRecord
object from a json response. The API I'm using returns a field called "id", but the type of "id" is a string, not a long (the backend is using mongo).
Below is the code I'm using:
Gson gson = new Gson(); // Or use new GsonBuilder().create();
NutritionPlan target = gson.fromJson(jsonObject.getJSONObject("nutrition_day").toString(), NutritionPlan.class);
Below is my json response:
{
"nutrition_day": {
"id": "5342b4163865660012ab0000",
"start_on": "2014-04-08",
"protein_target": 157,
"sodium_limit": 2000
}
Is there a good way to handle this scenario? I tried
@Ignore
long id;
and
@SerializedName("id")
String nutrition_plan_id;
in my model, but neither helped. Anyone familiar with Sugar ORM, and know how to deal with an id
field that isn't a long?
No big changes need be made.
Just use transient statement before Long type.
@SerializedName("id")
@Expose
private transient Long id;
Then, if you have getId and setId methods, should delete them.
And have fun!
Replace the key "id" in the string to be "nutrition_day_id". You can use the id json and the id sql.
jsonObject.getJSONObject("nutrition_day").toString().replace("\"id\"","\"nutrition_day_id\"")
It helped me to change id
name to mid
and add annotation @Expose
to all fields which have to be serialized and add annotation @SerializedName
to new id
field.
@SerializedName("id")
@Expose
private final String mid;
@Expose
private final String street;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With