0

我正在使用一个包含 JSON 的字符串,该字符串由 ASP Web 服务传递给 Android。我在我的 Android 应用程序中收到的字符串如下:

GetCustomerListResponse{GetCustomerListResult=[{"VehicleID":"KL-9876","VehicleType":"Nissan","VehicleOwner":"Sanjiva"}]; }

假设我想从 JSON 字符串中获取车辆类型,我该怎么做?

我完整的Android代码如下:

package com.example.objectpass;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import org.ksoap2.*;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.*;

public class MainActivity extends Activity {
    TextView resultA;
    Spinner spinnerC;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        String[] toSpinnerSum;
        toSpinnerSum = new String[9];

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        spinnerC = (Spinner) findViewById(R.id.spinner1);
        resultA = (TextView) findViewById(R.id.textView2);

        final String NAMESPACE = "http://tempuri.org/";
        final String METHOD_NAME = "GetCustomerList";
        final String SOAP_ACTION = "http://tempuri.org/GetCustomerList";
        final String URL = "http://192.168.1.100/WebService4/Service1.asmx";

        SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
        SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        soapEnvelope.dotNet = true;
        soapEnvelope.setOutputSoapObject(Request);
        AndroidHttpTransport aht = new AndroidHttpTransport(URL);

        try {
            aht.call(SOAP_ACTION, soapEnvelope);
            SoapObject response = (SoapObject) soapEnvelope.bodyIn;

            resultA.setText(response.toString());
        } 
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

任何帮助将不胜感激。谢谢

4

3 回答 3

1

您可以使用JSONObject类。教程可以在这里找到。相关问题在这里

于 2012-12-29T15:13:03.940 回答
1

将当前 Json 字符串解析为:

 //Convert String to JsonArray
 JSONArray jArray = new JSONArray(response.toString());

 for(int i=0;i<jArray.length();i++){
    // get json object from json Array
  JSONObject jsonobj = jArray.getJSONObject(i);

  //get VehicleType from jsonObject
   String str_VehicleType=jsonobj.getString("VehicleType");

  //get VehicleOwner from jsonObject
   String str_VehicleOwner=jsonobj.getString("VehicleOwner");

 }

有关我们如何在 android 中解析 josn 字符串的更多信息,请参见

http://www.technotalkative.com/android-json-parsing/

于 2012-12-29T15:31:20.877 回答
1

在这里,试试这个:

final int jsonBeginIdx = response.firstIndexOf("=");
final int jsonEndIdx = response.lastIndexOf(";");

if(jsonBeginIdx > 0 && jsonEndIdx > jsonBeginIdx) {
    final String jsn = response.substring(jsonBeginIdx + 1, jsonEndIdx);
    final JSONObject jsonObj = new JSONObject(json);
} else {
    // deal with malformed response here
}
于 2012-12-29T15:39:25.597 回答