Search code examples
javajsonpojo

Getting objects in a JSON response


I have a JSON response which looks like this:

String resp = "{"name":"Renold","age":"16"}"

And I have a POJO named "Person" which contains the attributes 'Name' and 'Age'. How do I extract the attributes from the JSON response and assign them to the POJO? I have already tried GSON and the object gets incorrectly assigned as "Name = name" and "Age = age" instead of the actual response.

Any other suggestions, good lads? :)

EDIT: This is what I used with GSON

Gson gson = new Gson(); 
final Person p= gson.fromJson(response, Person.class);

This left me with:

p.Name = name;

p.Age = age;

instead of p.Name = Renold.


Solution

  • I guess you have to use @SerializedName to map Name to name

    check this pojo parse gson with invalid java names

    In your Pojo you have to annotate like this.

      @SerializedName("name")
      private final Name;