2016-11-09 2 views
-1

У меня есть примеры данных json только с объектами.Android JSON Object Parsing

{ 
    "0": { 
    "image": null, 
    "title": "Government to issue new ₹500 and ₹2,000 notes from Nov 10 ", 
    "time": "10:46 pm ", 
    "date": "08 Nov ", 
    "content": "The government will start issuing the new ₹500 and ₹2,000 currency notes from November 10, said ...", 
    "link": "https://full-story.newsinshorts.com/v1/article/f0619b6a-738e-4470-897f-4e5cdad3ea52-1 " 
    }, 
    "1": { 
    "image": null, 
    "title": "₹1,000, ₹5,000 and ₹10,000 notes were demonetised in 1978 ", 
    "time": "10:20 pm ", 
    "date": "08 Nov ", 
    "content": "The Indian government had demonetised the ₹1,000, ₹5,000 and ₹10,000 currency notes in 1978 ...", 
    "link": null 
    }, 
    ... 

} 

У этого объекта больше объектов, чем видно. Как я могу продолжить анализ этих данных?

+1

Вы можете попробовать [этот пример] (http://stackoverflow.com/questions/22606572/android-json-parsing-of-multiple-jsonobjects- внутри-jsonobject), я вижу это почти так же, как ваш json. – NamNH

+1

Возможный дубликат [Как разобрать JSON в Android] (http://stackoverflow.com/questions/9605913/how-to-parse-json-in-android) –

+0

Почему вы пытаетесь разобрать это как класс модели, используя GSON и использовать эту модель – Saveen

ответ

0

Я принимаю выше JSON получается из данного источника сказать веб-сервер. Это как бы я справиться с этим

String yourJSON = { 
      "0": { 
      "image": null, 
      "title": "Government to issue new ₹500 and ₹2,000 notes from Nov 10 ", 
      "time": "10:46 pm ", 
      "date": "08 Nov ", 
      "content": "The government will start issuing the new ₹500 and ₹2,000 currency notes from November 10, said ...", 
      "link": "https://full-story.newsinshorts.com/v1/article/f0619b6a-738e-4470-897f-4e5cdad3ea52-1 " 
      }, 
      "1": { 
      "image": null, 
      "title": "₹1,000, ₹5,000 and ₹10,000 notes were demonetised in 1978 ", 
      "time": "10:20 pm ", 
      "date": "08 Nov ", 
      "content": "The Indian government had demonetised the ₹1,000, ₹5,000 and ₹10,000 currency notes in 1978 ...", 
      "link": null 
      }, 
      ... 

     }; 

     // create a JSON object to handle the response JSON 
     JSONObject yourJSONObject = new JSONObject(yourJSON); 

     /* 
     *this converts entire JSON object to JSON array since there is no further nesting 
     *this can be placed in a loop and the 0 replaced by an incremental variable say "int i" 
     */ 
     JSONArray data = yourJSONObject.getJSONArray(String.valueOf(0)); 

     // loop through the items in the first JSON array which in this case is only one therefore at index 0 
     for (int i = 0; i < data.length(); i++) { 
      // create JSON object to hold each item in array 
      JSONObject json = null; 

      try { 
       //Getting json 
       json = data.getJSONObject(i); 

       String image = json.getString("image"); 
       String title = json.getString("title"); 
       String time = json.getString("time"); 
       String date = json.getString("date"); 
       String content = json.getString("content"); 
       String link = json.getString("link"); 

       // perform action on this specific item 


      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
     } 
+0

Использует 'getJSONArray (0)' compile? –

+0

Согласно документации, этого метода не существует. Нет никаких массивов в этом JSON, anyways –

+0

Он компилируется, так как это фрагмент кода из одного из моих работающих проектов Android. –

0

Ok ...

попробовать что-то вроде этого ... просто дать вам идею ...

MyObject myObject = null; 
JSONObject object = new JSONObject(response); 
try{ 
    myObject = new MyObject(); 
    int position = 0; 
    while(position < 100){ 
     JSONObject jsonObject = object.getJSONObject(String.valueOf(position)); 
     String title = jsonObject.getString("title"); 
     myObject.setTitle(title); 

     ... 


     position++; 
    } 
}catch (JSONException e){ 
    return e.getMessage(); 
}finally{ 
    return myObject; 
} 
0

Попробуйте этот путь я имел то же самое ответ JSON и работать для меня

class LoadAllStates extends AsyncTask<String, String, ArrayList<String>> { 
    private ProgressDialog pDialog; 
    private String test; 
    private ArrayList<String> statedata; 
    private ArrayList<String> idadddata; 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(ShippingAddress.this.getActivity()); 
     pDialog.setMessage("Please wait.."); 
     pDialog.setIndeterminate(true); 
     pDialog.setCancelable(true); 
     pDialog.show(); 
    } 

    protected ArrayList<String> doInBackground(String... args) { 
     ServiceHandler sh = new ServiceHandler(); 
     // Making a request to url and getting response 
     statedata = new ArrayList<String>(); 

     idadddata = new ArrayList<String>(); 


     String jsonStr = sh.makeServiceCall(GET_ADDRESS_DETAIL, ServiceHandler.GET); 
     Log.d("Response: ", "> " + jsonStr); 
     if (jsonStr != null) { 
      try { 

       jsonObj = new JSONObject(jsonStr); 
       for (int i = 1; i <= jsonObj.length(); i++) { 

        JSONObject user = jsonObj.getJSONObject(""+i); 


        idaddress=String.valueOf(i); 
        System.out.println("userr"+i); 

        username= (user.has("name")) ? user.getString("name") : null; 
        usermobile= (user.has("mobile_number")) ? user.getString("mobile_number") : null; 
        useraddress= (user.has("address")) ? user.getString("address") : null; 
        userlandmark= (user.has("landmark")) ? user.getString("landmark") : null; 
        usercity= (user.has("city")) ? user.getString("city") : null; 
        userstate= (user.has("state")) ? user.getString("state") : null; 
        userpincode= (user.has("pin_code")) ? user.getString("pin_code") : null; 
        useremail= (user.has("email")) ? user.getString("email") : null; 
        if(username!=null) 
         statedata.add(username+","+usermobile+","+useraddress+","+userlandmark+","+usercity+","+userstate+","+userpincode+","+useremail); 

        idadddata.add(idaddress); 
        Log.i("inner",user.toString()); 
       } 
       System.out.println("WifeBday"+statedata.size()); 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
     } else { 
      Log.e("ServiceHandler", "Couldn't get any data from the url"); 
     } 
     return statedata; 
    } 

    protected void onPostExecute(ArrayList<String> result) { 
     super.onPostExecute(result); 
     pDialog.dismiss(); 
    } 
}