如何分离嵌入在Android字符串中的JSON对象?

时间:2012-12-29 15:08:59

标签: android json ksoap2

我正在使用包含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();
        }
    }
}

非常感谢任何帮助。感谢

3 个答案:

答案 0 :(得分:1)

您可以使用JSONObject课程。可以找到教程here。相关问题here

答案 1 :(得分:1)

将当前Json String解析为:

 //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/

答案 2 :(得分: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
}