1

I want to convert from JSon String to Java Object and print it to the console. but it's not working:

here is the code:

    try {
    //From JSON String to Java-Object (Json encoding)
    Person personObj = new Person(); 

    JSONObject json2Java = new JSONObject("{\"id\":1,\"fullName\":\"name\",\"age\":22}");
    personObj.setFullName(json2Java.getString("fullName"));
    personObj.setAge(json2Java.getInt("age"));
    personObj.setId(json2Java.getInt("id"));

    System.out.println("Json2Java: " + personObj);
    }
     catch (JSONException e) {
        throw new WebApplicationException(Response.status(Status.BAD_REQUEST)
                .entity("Couldn't parse JSON string: " + e.getMessage())
                .build());
    }

this is what I get on the console:

Json2Java: com.akapoor.ws.testws.model.Person@86fe26

Can you tell me where my mistake is and what I have to change?

Garis M Suero
  • 7,974
  • 7
  • 45
  • 68
user3428776
  • 33
  • 2
  • 10

3 Answers3

3

Your code is working correctly - however to get what you're looking for you need to override toString method in your Person object. Here's a simple implementation:

public String toString() {
     StringBuilder sb = new StringBuilder("Person:\n");
     sb.append("ID: ").append(this.getId()).append("\n")
        append("Full name: ").append(this.getFullName()).append("\n")
        append("Age: ").append(this.getAge()).append("\n");
     return sb.toString();
}

Add this to your Person object and execute the code again.

Aleks G
  • 56,435
  • 29
  • 168
  • 265
0
  • Override the toString() method inPerson` class to print the data in your required format.
  • The toString() method is called whenever an Object is printed to the console. Since your Person class does not have a toString() method, it calls the toString() method of the parent class, which in this case is Object and that prints the output that you see.
anirudh
  • 4,116
  • 2
  • 20
  • 35
0

Looks like you´re tring to ensure that your json is being correct parsed, so, your best try is to simple replace the personObj by the jsonToJava, because, once you get your json parsed the way you´re filling your pojo its will always be correct.

Sample:

System.out.println("Json2Java: " + json2Java);
Heitor
  • 190
  • 2
  • 13