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?

6
  • 1
    Can you add your exception, you get Commented Jul 29, 2016 at 10:14
  • I don't get any exception but the output is wrong Person@52b2a2d8 Shouldn't be the output is .json file data? Commented Jul 29, 2016 at 10:18
  • unless you put the output or error or exception we can not give a good answer. Commented Jul 29, 2016 at 10:19
  • Output is Person@52b2a2d8 Commented Jul 29, 2016 at 10:23
  • add toString() method in person class Commented Jul 29, 2016 at 10:24

3 Answers 3

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);
    }
Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.