Retrieve data from JSON Object using JSON Simple library

66 Views Asked by At

This is the JSON object printed to screen:

{"UserName":"myUsername","Address":"myAddress","Password":"myPassword"}

In the following code, what value goes in data_obj.get() & in obj.get() to retrieve UserName value myUsername from JSON Object?

JSONObject obj = (JSONObject) data_obj.get();
System.out.println(obj.get("UserName"));

I tried this

JSONObject obj = (JSONObject) data_obj.get(0);

//Get the required data using its key
System.out.println(obj.get("UserName"));

but I got null pointer and was expecting the data for UserName field equals myUsername.

1

There are 1 best solutions below

0
Alexander Ivanchenko On

You're probably performing a redundant step.

That's how the data you've shared can be parsed:

String jsonStr = """
        {"UserName":"myUsername","Address":"myAddress","Password":"myPassword"}
    """;
        
JSONObject jsonObject = new JSONObject(jsonStr);
        
System.out.println(jsonObject.get("UserName"));
System.out.println(jsonObject.get("Address"));
System.out.println(jsonObject.get("Password"));

Output:

myUsername
myAddress
myPassword