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?

2
  • 4
    Look into Object#toString() method. Then override it in your Person class. Commented Mar 18, 2014 at 14:57
  • In Eclipse you can generate it with ALT+SHIFT+S ans choose generate method toString Commented Mar 18, 2014 at 15:00

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Can u tell me that my client and service are right :
@user3428776 You don't have any client/service in your question - if you have issues with them, I suggest you post a separate question
The StringBuilder is redundant. You can use normal concatenation here.
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.

Comments

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);

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.