Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a String id with SugarORM and GSON

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?

like image 245
coder Avatar asked Apr 14 '14 20:04

coder


3 Answers

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!

like image 55
Arman Hosseini Avatar answered Oct 08 '22 01:10

Arman Hosseini


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\"")
like image 21
miguel savignano Avatar answered Oct 08 '22 01:10

miguel savignano


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;
like image 1
Serafins Avatar answered Oct 08 '22 02:10

Serafins