user3583884
user3583884

Reputation: 103

parsing JSON in JAVA can't access to value

I have a JSON string and U want to get the name and add fields. I've tried to use several libraries and follow many tutorials, but was unsuccessful.

I thing my problem is that i have several arrays together...

inputLine =
{"posts":[
    {"post":{
        "name":"name1",
        "add":"add1"}},
    {"post":{
        "name":"name2",
        "add":"add2"}}
    ]
}
JSONObject obj_posts = new JSONObject(inputLine);
JSONArray menuitemArray = obj_posts.getJSONArray("posts");
JSONObject obj_post = new JSONObject(menuitemArray.getJSONObject(0).toString());
JSONObject menuitem = obj_post.getJSONObject("post");
JSONArray obj_post1 = menuitem.names();

At this point I can only access the key name and add, not the values.

Upvotes: 0

Views: 72

Answers (3)

OnePunchMan
OnePunchMan

Reputation: 748

You need to import "org.json.JSONArray" , " org.json.JSONException", "org.json.JSONObject"

Also throws JSONException.

String obj_post1_name = "";
String obj_post1_add = "";
String obj_post2_name = "";
String obj_post2_add = "";
String inputLine =
        " {\"posts\":[{\"post\":{\"name\":\"name1\",\"add\":\"add1\"}},{\"post\":{\"name\":\"name2\",\"add\":\"add2\"}}]}";

        JSONObject obj_posts = new JSONObject(inputLine);
        JSONArray menuitemArray = obj_posts.getJSONArray("posts");
        JSONObject obj_post1 =(menuitemArray.getJSONObject(0));
        JSONObject obj_post2 =(menuitemArray.getJSONObject(1));
        JSONObject menuitem = obj_post1.getJSONObject("post");
        JSONObject menuitem2 = obj_post2.getJSONObject("post");
        obj_post1_name= menuitem.getString("name");
        obj_post1_add= menuitem.getString("add");
        obj_post2_name= menuitem2.getString("name");
        obj_post2_add= menuitem2.getString("add");

or you can use loop after:

JSONArray menuitemArray = obj_posts.getJSONArray("posts");
JSONObject obj_posts;
JSONObject menuitem;
for(int i=0;i<menuitemArray.length();i++){
    obj_posts= menuitemArray.getJSONObject(i);
    menuitem = obj_post1.getJSONObject("post");
    menuitem.getString("name");
    menuitem.getString("add");
}

Upvotes: 0

Hirak
Hirak

Reputation: 3649

The below code should work:

    System.out.println(menuitem.get(obj_post1.getString(0)));//Output name1
    System.out.println(menuitem.get(obj_post1.getString(1)));//Output add1  

Upvotes: 0

Hot Licks
Hot Licks

Reputation: 47699

JSONObject obj_posts = new JSONObject(inputLine);
JSONArray menuitemArray = obj_posts.getJSONArray("posts");
JSONObject obj_post = menuitemArray.getJSONObject(0);
JSONObject menuitem = obj_post.getJSONObject("post");
String postName = menuItem.getString("name");
String postAdd = menuItem.getString("add");

Upvotes: 1

Related Questions