JSON parse Android - object in object

左心房为你撑大大i 提交于 2019-12-12 04:46:47

问题


How to parse this json? I want get data from title, field_place and brothers fields.

{
"events": [
{
  "event": {
    "title": "BITUMIX Martyna Jastrz\u0119bska",
    "field_place": "Nowe Miejsce Al Jerozolimskie 51 lok.2",
    "field_zdjecie": "http:\/\/wybierzkulture.waw.pl\/sites\/default\/files\/styles\/post\/public\/martyna_jastrzebska_bitumix_2.jpg?itok=nd2O5U5z"
  }
},
{
  "event": {
    "title": "Wiecz\u00f3r Komedii Improwizowanej - D\u017cem Impro!",
    "field_place": "",
    "field_zdjecie": "http:\/\/wybierzkulture.waw.pl\/sites\/default\/files\/styles\/post\/public\/dzem_17_maja.jpg?itok=bfgDYxKq"
  }
}, 
...

I tried:

JSONObject itemm = jArray.getJSONObject(i);
JSONObject oneObject = itemm.getJSONObject("event");
String title = oneObject.getString("title");
String field_place = oneObject.getString("field_place");

... but it doesn't work.


回答1:


In a JSON string , there are two symbols that guide you through parsing :

{ - indicates a JSONObject

[ - indicates a JSONArray

When parsing a json string, you should go through this items iteratively. To understand how many JsonObjects and JsonArrays you have in your string , and from which you should start parsing, use a json-visualizer tool like this website. :

Example : As you see, the root object is a JSONObject which consists of an JSONArray with three jsonOnjects. To parse such a structure you can use :

JSONObject jsonobj = new JSONObject(jsonstring);

String result = jsonObject.getString("success");
String error_number = jsonObject.getString("error_number");    
String error_message = jsonObject.getString("error_message"); 

JSON Array jsonarray = jsonobj.getJSONArray();

String[] names = new String[jsonArray.length()];    
String[] formattedNames = new String[jsonArray.length()];  

for(int i=0;i<jsonArray.length();i++)
{
    JSONObject jsonObject = jsonArray.getJSONObject(i);

    names [i] = jsonObject.getString("name");
    formattedNames [i] = jsonObject.getString("formattedName");
  }



回答2:


try this

JSONArray  element = jsonobj.getJSONArray("events");
              for(int i=0;i < element.length();i++){    
                    JSONObject e = element.getJSONObject(i);


                    Log.d("TESTTT22",e.getJSONObject("event").getString("title"));

              }


        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


来源:https://stackoverflow.com/questions/23667072/json-parse-android-object-in-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!