Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse with GSON when identifier has space in name

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 ).

like image 927
Damir Avatar asked Aug 05 '11 23:08

Damir


People also ask

Does Gson ignore extra fields?

As you can see, Gson will ignore the unknown fields and simply match the fields that it's able to.

Why does Gson parse an integer as a double?

It sees all kind of numbers as a single type. That the numbers are parsed as a Double is an implementation detail of the Gson library. When it encounters a JSON number, it defaults to parsing it as a Double .

What does Gson toJson do?

Gson is the main actor class of Google Gson library. It provides functionalities to convert Java objects to matching JSON constructs and vice versa. Gson is first constructed using GsonBuilder and then toJson(Object) or fromJson(String, Class) methods are used to read/write JSON constructs.


1 Answers

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

like image 114
Eric Avatar answered Oct 13 '22 11:10

Eric