2017-10-05 21 views
-1

次のJSON応答文字列をサーバーから変換しようとすると、このエラーが発生します。私はJSONObjectを返すか、JSONArrayを処理したいのですが、JSONArrayを返す時間はほとんどの場合、サーバーからの応答に依存します。JSONオブジェクトをJSON配列に変換できません

org.json.JSONException: Value {"message":"No Results found!","status":"false"} of type org.json.JSONObject cannot be converted to JSONArray 
at org.json.JSON.typeMismatch(JSON.java:111) 
at org.json.JSONArray.<init>(JSONArray.java:96) 
at org.json.JSONArray.<init>(JSONArray.java:108) 

誰も私を助けることができます。サーバー

jsonString = {"message":"No Results found!","status":"false"} 

Javaコードから

JSONレスポンスは

try 
{ 
    JSONArray jsonArrayResponse = new JSONArray(jsonString); 
    if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) 
    { 
     if(jsonArrayResponse != null && jsonArrayResponse.length() > 0) 
     { 
      getCancelPurchase(jsonArrayResponse.toString()); 
     } 
    } 
} 
catch(JSONException e) 
{ 
    e.printStackTrace(); 
} 

エラーログ以下の通りです。

おかげ

+0

JsonArray列repsentationは、[」で始まります"とjsonObject startswith" {"にはもう少しの違いがありますので、googleにしてください – nafas

答えて

3

String data = "{ ... }"; 
Object json = new JSONTokener(data).nextValue(); 
if (json instanceof JSONObject) 
    //you have an object 
else if (json instanceof JSONArray) 
    //you have an array 
+0

ありがとうございました。 –

2

あなたの応答{"message":"No Results found!","status":"false"}は配列ではありません。それはオブジェクトです。コードにJSONArrayの代わりにJSONObjectを使用してください。

ヒント:配列は角括弧[]で囲まれ、オブジェクトは中括弧{}で囲まれます。あなたが行うことができます1を、答えるためにあなたのコメントに基づいて

+0

私はまた、製品のJSONArrayも期待しています。 JSONArrayとJSONObjectの両方を同時に処理するにはどうすればよいですか? –

+0

@nafasによってコメントされました。 JsonArray文字列repsentationは "["とjsonObject startswith "{"から始まります。私はあなたがそれを理解できることを願っています。 –

0

私は、コードを以下の書き込みによってこの問題を解決された[礼儀@optional]

String jsonString = "{\"message\":\"No Results found!\",\"status\":\"false\"}"; 
/* String jsonString = "[{\"prodictId\":\"P00001\",\"productName\":\"iPhone 6\"}," 
     + "{\"prodictId\":\"P00002\",\"productName\":\"iPhone 6 Plus\"}," 
     + "{\"prodictId\":\"P00003\",\"productName\":\"iPhone 7\"}]"; 
*/ 
JSONArray jsonArrayResponse; 
JSONObject jsonObject; 
try { 
    Object json = new JSONTokener(jsonString).nextValue(); 
    if (json instanceof JSONObject) { 
     jsonObject = new JSONObject(jsonString); 
     if (jsonObject != null) { 
      System.out.println(jsonObject.toString()); 
     } 
    } else if (json instanceof JSONArray) { 
     jsonArrayResponse = new JSONArray(jsonString); 
     if (jsonArrayResponse != null && jsonArrayResponse.length() > 0) { 
      System.out.println(jsonArrayResponse.toString()); 
     } 
    } 
} catch (JSONException e) { 
    e.printStackTrace(); 
} 
関連する問題