2013-05-01 90 views
1

我有一个json对象,它被作为字符串收集到一个函数中。
它包含阵列将json解析值存储为数组中的字符串

{ “officer_name”: “VM ARORA”} { “officer_name”: “博士CP REDDY。”} { “officer_name”: “ARTI CHOWDHARY”} { “officer_name”:” JAGDISH SINGH“}

这里是Android代码

public void func4(View view)throws Exception 
{ 
    AsyncHttpClient client = new AsyncHttpClient(); 
    RequestParams rp = new RequestParams(); 
    rp.put("pLat", "SELECT officer_name FROM iwmp_officer"); 

    client.post("http://10.0.2.2/conc5.php", rp, new AsyncHttpResponseHandler() { 
     public final void onSuccess(String response) { 
      // handle your response here 
      ArrayList<String> User_List = new ArrayList<String>(); 
      try { 
       /* here I need output in an array, 
       and only names not the "officer_name" */ 
      } catch (Exception e) { 
       tx.setText((CharSequence) e); 
      } 

      //tx.setText(User_List.get(1)); 
     } 

     @Override 
     public void onFailure(Throwable e, String response) { 
      // something went wrong 
      tx.setText(response); 
     }    
    }); 
} 

我上面显示的是在字符串的输出,需要把它的阵列。请帮忙!

+0

做一些研究JSON。 'JSONArray'会做你需要的。此外,你已经显示在上面的JSON无效 – Naveen 2013-05-01 11:03:46

回答

1

如果你得到的输出是这样的。它的一个JSON数组。 您可以分析它作为

JsonArray array=new JsonArray(outputJson); 

然后循环使用

for(JsonObject jsonObj in array){ 

String officerName=[jsonObj getString("officer_name"); 

} 

您可以使用类似上面的提到的代码没有语法正确此JSON阵列,但在概念上是正确的。你可以继续这个。

1
List <String> ls = new ArrayList<String>(); 
JSONArray array = new JSONArray(response); 

for (int i = 0; i < array.length() ; i++) { 
    JSONObject obj = array.getJSONObject(Integer.toString(i)); 

    ls.add(obj.getString("officer_name")); 
} 

这会工作

+0

请注意其他人的问题,谢谢。 – yug 2013-05-01 11:58:59

+0

PLZ检查我的其他问题,http://stackoverflow.com/questions/16353561/java-net-socketexceptionoperation-time-out-when-running-app-on-real-device – yug 2013-05-03 09:26:40

0
try { 
        JSONArray array= new JSONArray(response); 
        //array = new JSONArray(response); 
         for (int i = 0; i < array.length(); i++) { 
          //JSONObject obj = response.getJSONArray(i); 
          JSONObject jsonLineItem = (JSONObject) array.getJSONObject(i); 
          String name_fd = jsonLineItem.getString("officer_name"); 
          User_List.add(jsonLineItem.getString("officer_name")); 
          Log.d("JSONArray", name_fd+" " +name_fd); 

         } 


       } catch (JSONException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
        tx.setText(e.toString()); 
       }