Skip to content
Advertisement

Is toString() mandatory while accessing the individual element of a JSON object in Java

I am quite new to Java and trying to understand the effect of using toString() while accessing the individual string elements of JSON object in Java.

Below are the steps followed:

  1. Parse the JSON data. Let’s assume only string elements are there in parsed JSON data.
JSONParser parser = new JSONParser();
JSONObject jsonObj = (JSONObject) parser.parse(json_data);
{
   "firstname" : "new",
   "lastname" : "human",
   "id" : "some_id"
}
  1. Try to access the individual elements.
    Access without toString():
    Public static String firstname = jsonObj.get("firstname");
    Access with toString():
    Public static String firstname = jsonObj.get("firstname").toString();

I do not see a difference when I try to print the data.
However I would like to know the difference between the above 2 methods, and also will there be any issues if I use without toString() in this particular case.

Appreciate your help.

Thank you

Advertisement

Answer

When you have some Int or other type of data type variables in your model class and you want to parse it into a string so for that we use toString(), it will convert int or any other data variable into a string, in your case here you already have string so no need to change again and again and JSON uses string variables when it comes from backend so that the purpose.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement