-2

i'm posting some data to a web service and i'm getting a json reply which i want to pass to a jsonobject.

The reply of the web service is:

{
    "ValidateLoginResult": [
        {
            "ErrorMessage": "Wrong username pass",
            "PropertyName": null
        }
    ]
}

and i want to pass the error message and the property name to variables. I tried using JSONobject and JSONarray but didnt have any luck

                HttpClient httpclient = new DefaultHttpClient();

                // 2. make POST request to the given URL
                HttpPost httpPost = new HttpPost(serverURL);
                StringEntity se = new StringEntity(data);
                httpPost.setEntity(se);

                // 7. Set some headers to inform server about the type of the content
                httpPost.setHeader("Accept", "application/json");
                httpPost.setHeader("Content-type", "application/json");

                // 8. Execute POST request to the given URL
                HttpResponse httpResponse = httpclient.execute(httpPost);
                // 9. Getting Reply
                inputStream = httpResponse.getEntity().getContent();
                ...
                ...
                 JSONArray json = new JSONArray(convertInputStreamToString(inputStream));



                JSONObject json_LL = json.getJSONObject(0);

                String str_value=json_LL.getString("ErrorMessage");
Pragnesh Ghoda シ
  • 8,318
  • 3
  • 25
  • 40
Mike
  • 21
  • 4

1 Answers1

0

You are getting response in JSONObject and you are trying to get it in JSONArray.. thats why you are getting error..

Try this way...

try {
    JSONObject result = new JSONObject(response);

    if(data.has("ValidateLoginResult"){
        JSONArray array = result.getJSONArray("ValidateLoginResult");

        for (int i = 0; i < array.length(); i++) {
        JSONObject obj = array.getJSONObject(i);
            String ErrorMessage= ""+obj.getString("ErrorMessage");
            String PropertyName= ""+obj.getString("PropertyName");
        }
    }

} catch (JSONException e) {
    e.printStackTrace();
}

OR

if you want one line answer..Try this..

// going directly to array object..
JSONObject result = new JSONObject(response).getJSONArray("ValidateLoginResult").getJSONObject(0);

String ErrorMessage= ""+result.getString("ErrorMessage");
String PropertyName= ""+result.getString("PropertyName");
Pragnesh Ghoda シ
  • 8,318
  • 3
  • 25
  • 40