Json Iteration 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 have id and module_name with the following code. How can I get user_default_dateformat ?.

I know it can be that simple, but I'm new to 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(); 

Create exception generation

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

Eexception -

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

Thanks,

+4
source share
2 answers

name_value_list is also an object.

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

So you get

 job2.get("user_default_dateformat"); 

Each {} in your JSON is an object. So, for every line you get, something like {"xy":"za","ab":"cd"} , you should send it to JSONObject

Edit for your error:

As you see in your code line:

 JSONObject job2=new JSONObject(job); 

will try to create a JSONObject from your JSONObject.

You should get a JSONObject in your JSONObject.

You want to get 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 
+4
source

If you are using the 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 will give you the desired result.

+1
source

Source: https://habr.com/ru/post/1494201/


All Articles