2

I currently have the following JSON:

{"content":
    [{"uuid":"123132",
    "firstname" : "Jon",
    "lastname" : "Deer"
     ...
     }
    ]
}

What I am trying to do is use Java to get the string value of "uuid". The following is my code:

JSONPATH jsonPath = new JSONPATH(json);
String myString = jsonPath.getString("content.uuid");
System.out.println(myString);

The resulting string: [123132] The expected string: 123132

Is there another way to get the expected result using JSONPATH without using substring (removing the first and last characters of the string) since it is a bit more messy to look at the code?

0

3 Answers 3

8

Due to content being an array, "content.uuid" returns a list of string. However, as we are calling getString() method, that list is converted into String (using toString()) and hence, we are getting [123132] as a result.

Correct way to get the first value is jsonPath.getString("content[0].uuid");

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

1 Comment

And what should we do if we want to get whole string from jsonPath? When we use jsonPath.getString("$") we are getting all object inside root object. But we want whole root object.
1

Return value of jsonPath is an array, which is also a valid JSON structure. If you need the data as an other type, e.g. a String in this case, you will have to do the conversion yourself get your value#

Check this page for sample and why it returns array.

Comments

0

have u ever tried google.simple.Json Jar ? This Jar can easily enables u to read this JSONObject Easily.

                       {
                         "content":
                           [{"uuid":"123132",
obj_ComplexJson ==>          "firstname" : "Jon",
                             "lastname" : "Deer"
                              ...
                            }],[],[],[]
                        }
 JSONObject obj_ComplexJson = "{"content":[{}]}""; //this json object contains your Actual Object.
JSONParser parser = new Parser();
JSONArray obj_arr = (JSONArray)parser.parse(obj_ComplexJson.get("content"));
 for(JSONObject eachObj : obj_arr){
         System.out.println(eachObj.get("uuid"));
          ..........
          ..........
     }

Get Maven JSON Simple Maven or Direct Jar File

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.