How to parse with GSON when identifier has space in name

与世无争的帅哥 提交于 2019-11-26 16:55:41

问题


How to parse with GSON when file looks like this

{
    "Person Id":"test",
    "Last Name": "test",
    "First Name":"test"
}

I know to parse when names doesn't have space between, I create class like

class Person{
public String PersonId;
public String LastName;
public String FirstName;
}

but how to parse when identifier has space inside ? What to change in Person class ? ( I cannot change format of file ).


回答1:


I have tried to parse this JSON but I didn't use GSON to parse this. I'll share my code with you, kindly consider only as a supplementary solution to solve the issue:

String parse = "{\"Person Id\":\"test\",\"Last Name\": \"lname\",\"First Name\":\"fname\"}";
try {
    JSONObject jsonObject   =   new JSONObject(parse);
    String id = jsonObject.getString("Person Id");
    System.out.println("id="+id);
    System.out.println("lname="+jsonObject.getString("Last Name"));
    System.out.println("fname="+jsonObject.getString("First Name"));
} catch (JSONException e) {
    e.printStackTrace();
}



回答2:


While still using GSON you can do this by adding an annotation. For instance:

class Person{
    @SerializedName("Person Id") public String PersonId;
    @SerializedName("Last Name") public String LastName;
    @SerializedName("First Name") public String FirstName;
}

You can find more details in the GSON documentation: https://sites.google.com/site/gson/gson-user-guide#TOC-JSON-Field-Naming-Support



来源:https://stackoverflow.com/questions/6963553/how-to-parse-with-gson-when-identifier-has-space-in-name

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