Search code examples
androidjsonksoap2

How do I separate out a JSON object embedded within a string for Android?


I am consuming a string containing JSON, which is passed by an ASP web service to Android. The string that I receive in my Android app is as follows:

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

Say I want to get the vehicle type from the JSON string, how do i do that?

My complete Android code is as follows:

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();
        }
    }
}

Any help would be greatly appreciated. Thanks


Solution

  • Parse current Json String as:

     //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");
    
     }
    

    and for more info how we parse an josn string in android see

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