从JSON数组中提取值

时间:2015-09-08 06:35:15

标签: android json

我试图从JSon数组中提取值。我上面的代码显示了"响应"在textview中。我目前在[{"JsonOutput":"Er"}]的回复为textview。我想提取Er并设置为TextView

  public void onCreate(Bundle savedInstanceState) {

        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
            }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvData1 = (TextView)findViewById(R.id.textView1);


        button=(Button)findViewById(R.id.button1);

        button.setOnClickListener(new OnClickListener() {

            @SuppressLint("NewApi")
            public void onClick(View v) {
                  SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,     OPERATION_NAME);
                    PropertyInfo propertyInfo = new PropertyInfo();
                    propertyInfo.type = PropertyInfo.STRING_CLASS;
                    propertyInfo.name = "eid";

                    edata =(EditText)findViewById(R.id.editText1);
                    studentNo=edata.getText().toString();

                    request.addProperty(propertyInfo, studentNo);

                            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                            SoapEnvelope.VER11);
                            envelope.dotNet = true;

                            envelope.setOutputSoapObject(request);

                            HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);

                            try  {                    
                            httpTransport.call(SOAP_ACTION, envelope);                    
                            Object response = envelope.getResponse();                    
                            tvData1.setText(response.toString());

                           // Do here something to extract value (Er) from the key:value pair. 





                            }  catch (Exception exception)   {
                                          tvData1.setText(exception.toString());                    
                            }

                    tvData1 = (TextView)findViewById(R.id.textView1);

            }
        });



 }
}

2 个答案:

答案 0 :(得分:0)

使用JSONObject

获取"JsonOutput"字符串
try{            
    JSONArray root = new JSONArray(response);
    for (int i = 0; i < root.length(); i++) {
        JSONObject att = (JSONObject) root.getJSONObject(i);
        String ouput= att.getString("JsonOutput");
    }
}catch (JSONException e) {
    e.printStackTrace();
}

答案 1 :(得分:0)

如果你得到JSONArray

 JSONArray response = new JSONArray(envelope.getResponse().toString()); 

否则,如果你得到JSONObject

 JSONObject response = new JSONObject(envelope.getResponse().toString());
如果需要,

覆盖你的.toString()方法。

现在你可以在数组的情况下拥有response[0].getString("JsonOutput"),如果是对象你可以拥有response.getString("JsonOutput")并且是的,因为评论中提到的人没有在主线程上进行网络调用。< / p>