0

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?

Bilesh Ganguly
  • 3,792
  • 3
  • 36
  • 58

3 Answers3

2

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);
    }
nafas
  • 5,283
  • 3
  • 29
  • 57
1

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?

Community
  • 1
  • 1
Jekin Kalariya
  • 3,475
  • 2
  • 20
  • 32
0

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
}
sushi
  • 139
  • 1
  • 9
gowtham
  • 26
  • 2