2016-08-10 4 views
1

非同期リクエスト(REST query)を実行します。サーバ側からの応答が...JSONへのレスポンスを続ける方法

[{"id":2,"name":"Flowers"},{"id":3,"name":"Trees"}] 

で取得私はJSONObjectに応答文字列を解析する必要がありますし、データを取得する私の次のasync方法(いくつかのコードをコメント化されている)で

ArrayList<Map<String, String>> 

へ:

//async getting data 
@Override 
public void onSuccessResult(String response) { 
    String message; 
    Log.d(Constants.LOG, response); 
    try { 
     JSONObject jsonResponse = new JSONObject(response); 

/* 
      JSONArray jsonArray = jsonResponse.getJSONArray("id"); 
      data.clear(); 
      for(int i=0;i<jsonArray.length()-1;i++){ 
       HashMap<String, String> m = new HashMap<String, String>(); 
       JSONArray url = jsonArray.getJSONArray(i); 
       m.put("name", url.getString(0)); 
       dataPlants.add(m); 

      //sAdapter.notifyDataSetChanged(); 

*/ 

    }catch (JSONException e) { 
     Log.d(Constants.LOG, e.toString()); 
     e.printStackTrace(); 
    } 

私は次のexception取得:

org.json.JSONException: Value 
[{"id":2,"name":"Flowers"},{"id":3,"name":"Trees"}] of type org.json.JSONArray cannot be converted to JSONObject 

だから、どのように適切に

答えて

2

問題は、あなたががJSONArrayあなたがJSONArrayとして文字列を解析する必要が
を表す文字列からJSONObjectを作成しようとしているという事実から来ているresponseを進みます。

JSONObject jsonResponse = new JSONObject(response); 

編集@

jsonResponse = new JSONArray(response); 
//data.clear(); 
for (int i = 0; i < jsonResponse.length(); i++) { 
    Object obj = jsonResponse.get(i); 
    if(obj instanceof JSONObject) { 
      HashMap<String, String> m = new HashMap<>(); 
      JSONObject object = jsonResponse.getJSONObject(i); 
      m.put(object.getString("id"), object.getString("name")); 
      dataPlants.add(m); 
    } 
} 
//sAdapter.notifyDataSetChanged(); 

JSONArray jsonResponse = new JSONArray(response); 

する必要があります:オブジェクトの検証がそこにあるのでまた、私は、コードをeditted。
正直なところ、両方がそれを助けています

+0

異なる解析メカニズムを持っているので、あなたが、オブジェクトとして扱い、彼らはJSONObjectまたはJSONArrayのインスタンスのインスタンスであるかどうかを確認する必要がありJSONファイル、で処理する時はいつでも。どうもありがとう。 – Maksim

+0

@Maksimこの男は本当の答えを投稿する –

+0

@Maksimそれが働いたことを知ってよかった!答えを受け入れたものとしてマークし、他の人がバグを修正するのに役立つかもしれないようにします。よろしく –

関連する問題