rplg
rplg

Reputation: 232

Json Iterating using java

Here is my json Object.

{"id":"mrbbt6f3fa99gld0m6n52osge0",
 "name_value_list":
 {"user_default_dateformat":{"name":"user_default_dateformat","value":"m/d/Y"}},
 "module_name":"Users"}    

I got id,and module_name through following code.How can i get user_default_dateformat?.

I know it may so simple but I am a newbie in json.

        String jsonResponse;

        while ((jsonResponse = br.readLine()) != null) {

            jsonOutput = jsonResponse;

        }
        JSONObject job = new JSONObject(jsonOutput);

        System.out.println(job);// i can see the same json object 
                                                that i showen above.
        sessionID = job.get("id").toString();

Exception generating coge

JSONObject job2=new JSONObject(job);
dateFormat = job2.get("user_default_dateformat").toString();

The Eexception is

org.json.JSONException: JSONObject["user_default_dateformat"] not found.    

Thanks,

Upvotes: 4

Views: 99

Answers (2)

shamik
shamik

Reputation: 24

if you are using JSONSimple library you can use this:

jsonObject = (JSONObject) new JSONParser().parse(jsonstr); System.out.println((JSONObject)jsonObject.get("name_value_list"))).get("user_default_dateformat"));

This should give you the required result.

Upvotes: 1

Loki
Loki

Reputation: 4130

name_value_list is also an Object.

JSONObject job2 = new JSONObject(job.get("name_value_list"));

So there you get

job2.get("user_default_dateformat");

Every {} in your JSON is an object. So for every String you get which is something like {"xy":"za","ab":"cd"} you have to cast it to the JSONObject

Edit for your error:

As you can see in your code the line:

JSONObject job2=new JSONObject(job);

will try to generate a JSONObject out of your JSONObject.

You have to get the JSONObject in your JSONObject.

You want to get the user_default_dateformat which is in your JSONObject:

String name_value_list_string = job.get("name_value_list").toString();
//this string is another json-string which contains the user_default_dateformat
JSONObject name_value_list_object = new JSONObject(name_value_list_string);

//This JSONObject contains the user_default_dateformat but this is also a JSONObject

String user_default_dateformat_string = name_value_list_object.get("user_default_dateformat").toString();
//this String contains the user_default_dateformat JSONString

JSONObject user_default_dateformat_object = new JSONObject(user_default_dateformat_string);

//This JSONObject contains the String values of your user_default_dateformat

Upvotes: 4

Related Questions