Parsing a String id with SugarORM and GSON

喜你入骨 提交于 2019-12-10 02:21:31

问题


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?


回答1:


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\"")



回答2:


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;



回答3:


I've been concerned with the same problem, and the only solution i've found was to rename the id name from my API. From example try to send nutrition_plan_id instead of id from your API and it would done the job.




回答4:


Here is my solution, but it won't be the best.

I just ignored id in my Feed

public class Feed extends SugarRecord<Feed>  {

  @Expose int idMember;
}

It works fine, however the real id is no more used.




回答5:


I was looking for a solution to this problem for quite some time. Finally I found a solution to it. Simply add @Table annotation to the desired class instead of extending it from SugarRecord and manually add id attribute. You can exclude it from Gson serialization via transient keyword, or/and rename it, with @SerializedName annotation.

Example (works fine for me on SugarOrm v1.4):

@Table
public class MySugarOrmClass{

    @SerializedName("db_id")
    private transient Long id = null;

    @SerializedName("id")
    private Integer aid;

    // Add an empty constructor
    public MySugarClass(){}


    //Other fields and class attributes
    ...
}

But this means that you cannot use .save(), .delete(), etc. methods on this class. Instead you have to use SugarRecord's static methods: SugarRecord.save(), SugarRecord.delete(),...



来源:https://stackoverflow.com/questions/23069799/parsing-a-string-id-with-sugarorm-and-gson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!