Nehir Akbaş
Nehir Akbaş

Reputation: 1

Parsing JSON File to Java with GSON

I am trying to parse a JSON file to Java with GSON and i have problem

Gson gson = new GsonBuilder().create();
Person p1 = gson.fromJson(new FileReader("/Users/blabla/Desktop/person.json"), Person.class);
System.out.println(p1);

This is my Person class

public class Person {
    private String name;
    private int age;
    private List<String> Friends; 

    //Getters and setters

This is my JSON File

{
  "Name":"TEXT",
  "Weight":95,
  "Height":1.87,
  "Friends":[
    "FRIEND1",
    "FRIEND2",
    "FRIEND3"
  ]
}

Output is Person@52b2a2d8

What am I doing wrong?

Upvotes: 0

Views: 98

Answers (3)

gowtham
gowtham

Reputation: 26

1)Your attribute names should match with the JSON values

2)Right click in eclipse and generate toString() method.

Ex: person class should be

public class Person {
    String name;
    int age;
    List<String> friends

    //Getters and setters
}

Upvotes: 0

nafas
nafas

Reputation: 5423

naming matters.... you need to make sure JSON keys are identical to your class attributes (lowercase/uppercase) etc...

either change your JSON to

{ "name":"TEXT", "Weight":95, "Height":1.87, "Friends": [ "fRIEND1", "FRIEND2", "FRIEND3" ] }

or change your Person class attributes

private String Name;
private int age;
private List<String>Friends; 

in addition you need to Override toString method in your Person class to get nice Print

e.g.

add this to your Person class:

    @Override
    public String toString() {

        return (name + " : " + age + " : " + Friends);
    }

Upvotes: 2

Jekin Kalariya
Jekin Kalariya

Reputation: 3507

If Person class doesn't have toString method than of course result will like this.you need override toString() for that.

You can see about toString() here How to use the toString method in Java?

Upvotes: 1

Related Questions