Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json object contain json array parsing

Tags:

java

json

Am using a function to add list items,name ,id into a jsonobject and returning that object into called function,and getting all the way..But i am little confused with parsing of that json string.

JSONObject obj = abcobj.function();

public JSONObject function()
{
  jsonobj.put("test",list);
  jsonobj.put("name",name);
  jsonobj.put("id",id);
  return jsonobj;
}

System.out.println("Json object"+devid);

Output

 {"test":["test","test1"],"name":"xxxxx","id":"1234"}

please help me to parse this object

like image 287
Aravind Cheekkallur Avatar asked Jan 26 '26 19:01

Aravind Cheekkallur


2 Answers

create an instance of JSONObject class and using for loop through each json item and finally storing each json data in variable.

JSONObject jsonRoot = new JSONObject(jsonData);
  List<String> list = new ArrayList<String>();    
  JSONArray jsonList = jsonRoot.getJSONArray("test");
 for (int i = 0; i < jsonList.length(); i++) {
          list.add(jsonList.getString(i));
   }
 String str_name = jsonRoot.getString("name");
 Integer str_id = Integer.valueOf(jsonRoot.getInt("id"));

Hope this will help you.

like image 100
GrIsHu Avatar answered Jan 28 '26 11:01

GrIsHu


If you're using the org.json. Java parser, here's how to do it:

String jsonData = "{\"test\":[\"test\",\"test1\"],\"name\":\"xxxxx\",\"id\":\"1234\"}";

JSONObject jsonRoot = new JSONObject(jsonData);

List<String> list = new ArrayList<String>();    
JSONArray jsonList = jsonRoot.getJSONArray("test");
for (int i = 0; i < jsonList.length(); i++) {
  list.add(jsonList.getString(i));
}

String name = jsonRoot.getString("name");
Integer id = Integer.valueOf(jsonRoot.getInt("id"));
like image 43
Ravi K Thapliyal Avatar answered Jan 28 '26 10:01

Ravi K Thapliyal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!