2016-08-21 11 views
0

いくつかのJSONデータを抽出して処理しようとしていますが、試してみるとエラーになります。これは私のコードです:JSONArrayをJSONObjectに変換中にエラーが発生しました

protected void onPostExecute(String s) { 
    String err=null; 
    try { 
     JSONObject root = new JSONObject(s); 
     JSONObject user_data = root.getJSONObject("user_data"); 
     LASTNAME = user_data.getString("lastname"); 
     PASSWORD = user_data.getString("password"); 
     EMAIL = user_data.getString("email"); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
     err = "Exception: "+e.getMessage(); 
    } 
    Intent i = new Intent(ctx, MainActivity.class); 
    i.putExtra("lastname", LASTNAME); 
    i.putExtra("email", EMAIL); 
    i.putExtra("password", PASSWORD); 
    i.putExtra("err", err); 
    startActivity(i); 
} 

しかし、これは誤りである:それはあなたの「のuser_data」のように思える

org.json.JSONException: Value [] at user_data of type org.json.JSONArray cannot be converted to JSONObject

error output

+0

logcatにはどのような値がありますか –

+0

logcatをいくつかのlog.d( "rootval"、root)で貼り付けることができます。 –

+0

あなたの応答もここに追加しますか?それから私たちは助けることができます。 –

答えて

-1

は、あなたがしようとしている代わりに、JSONオブジェクトのJSON配列として来ていますアクセスするために。

&あなたのuser_dataがjsonオブジェクトであるか、nullを返す場合は、root.optJSONObject("user_data")を使用して確定することができます。

+0

どうすればいいですか root.optJSONObject( "user_data")が機能していません –

1

オブジェクトをArrayにキャストする際に問題があると思います。

[..]はJSONArrayを意味します。

{..}はJSONObjectを意味します。

try { 
    JSONArray jObj = new JSONArray(json); 
    //This is how you get value from 1 element in JSONArray 
    String firstObjectValue = jObj.getString(0); 

} catch (JSONException e) { 
    Log.e("JSON Parser", "Error parsing data " + e.toString()); 
} 

あなたが値を探している場合

はあなたには、いくつかの単純なループを実行して、すべてのJSONArray を反復処理する必要があります。

JSONObject jsonObject = null; 
    try { 
     jsonObject = new JSONObject(result); 
     JSONArray jsonARRAY = jsonObject.getJSONArray("nameOfJSONArray"); 
     for (int i = 0; i < jsonARRAY.length(); i++) { 
      JSONObject jsonOBJECT = (JSONObject) jsonARRAY.get(i); 
      String yourValue = jsonOBJECT.getString("valueKey"); 

     } 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
関連する問題