2

JSON応答を次のように受け取ります

{
"edges": [],
"nodes": []
}

オブジェクトにnull値があるかどうかを確認し、ケースを処理する方法は??

JSONObject jobj = new JSONObject(line);
JSONArray jArray = jobj.getJSONArray("edges");
if(jArray.length()!=0)
{    
  for(int i=0;i<jArray.length();i++){
  JSONObject json_data = jArray.getJSONObject(i);
  x.add((float) json_data.getInt("x"));
  y.add((float) json_data.getInt("y"));
end

これは私を元に戻します:org.json.JSONException:の文字0での入力の終わり

4

4 に答える 4

3

try this one:

String jsonString = "{ "edges": [], "nodes": [] }";

JSONObject jsonObject = new JSONObject(jsonString);

if( jsonObject.isNull("edges") == false) {
//do sth
}

if( jsonObject.isNull("nodes") == false) {
//do sth
}

you can also check if you have some particular key in your json by jsonObject.has("edges")

you are passing some \line\ variable to the JSONObject constructor. make sure that this variable contains your whole json string like this one in my example and not something like "{" or ' "edges": [] ' maybe the problem is in your json source like dokkaebi suggested in comment

于 2012-12-05T21:03:40.723 に答える
2

you can check as:

JSONObject jobj = new JSONObject(line);
if (jobj.getJSONArray("edges").length() == 0) {

    System.out.println("JSONArray is null");      
 }
 else{
      System.out.println("JSONArray is not null");
      //parse your string here         
     }
于 2012-12-05T19:55:41.317 に答える
2

try this on. I am showing example only for only one array depending on flag value you can show proper error message or on success you can bind parsed data to UI component.

String impuStr = "{\"edges\": [],\"nodes\": []}";

String flag = serverResponse(impuStr);

private String serverResponse(String jsonStr) { String flag = "success";

    JSONObject jobj;
    try {
        jobj = new JSONObject(jsonStr);

        JSONArray jArrayEdges = jobj.getJSONArray("edges");
        if(jArrayEdges != null && jArrayEdges.length() > 0)
        {    
          for(int i=0;i<jArrayEdges.length();i++)
          {
              JSONObject json_data = jArrayEdges.getJSONObject(i);
              // process data here
          }
         }else
             flag = "edges_list_empty";

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

    return flag;
}
于 2012-12-06T11:02:17.123 に答える
0

単純なJavaルールを使用します。配列が空かどうかを確認します。配列が存在しない場合は、配列を取得しようとすると、nullが返されます。ただそれを処理します。失敗することがわかっている場合は、解析を続行しないでください。ただ優雅に存在しなさい。

if (myObj != null)
{
  ... process
}
于 2012-12-05T19:52:27.917 に答える