0

I am working with webservice in an android app. I could not parse the following response in app. it always gives the

org.json.JSONException: Value [{"METER_READING":"15","UTILITY_PLAN":"1","uname":"vinayak@triffort.com","kwh_usage":"3","meter_reading_date":"02-13-2014","ESID":"abc","METER_ID":"abc100"}] at data of type java.lang.String cannot be converted to JSONArray.

Below is my code:

StringEntity entity = new StringEntity(jsonObject.toString(), HTTP.UTF_8);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader =new BufferedReader(new   InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String jsonResultStr = reader.readLine();
JSONObject jObject = new JSONObject(jsonResultStr);
JSONArray jArray = jObject.optJSONArray("data");

I get following response from webservice

{"data":"[{\"METER_READING\":\"25\",\"UTILITY_PLAN\":\"1\",\"uname\":\"vinayak@triffort.com\",\"kwh_usage\":\"9\",\"meter_reading_date\":\"02-13-2014\",\"ESID\":\"abc\",\"METER_ID\":\"abc100\"}]"}

vokilam
  • 10,153
  • 3
  • 45
  • 56
user8938
  • 559
  • 1
  • 4
  • 12
  • which response are you getting? – Blackbelt Feb 13 '14 at 10:50
  • check: http://stackoverflow.com/questions/21480634/unable-to-loop-through-dynamic-json-string-recursively-in-android/21480997#21480997 – Pararth Feb 13 '14 at 10:53
  • {"data":"[{\"METER_READING\":\"25\",\"UTILITY_PLAN\":\"1\",\"uname\":\"vinayak@triffort.com\",\"kwh_usage\":\"9\",\"meter_reading_date\":\"02-13-2014\",\"ESID\":\"abc\",\"METER_ID\":\"abc100\"}]"} from webservice – user8938 Feb 13 '14 at 10:55

5 Answers5

0

try this simple code:

JSONObject o = new JSONObject(new JSONTokener(postResponse));
JSONArray ja = o.getJSONArray("data");

EDIT

Thanks @McDowell for observation

new JSONArray(new JSONTokener(jObject.optString("data")));
Siruk Viktor
  • 504
  • 1
  • 8
  • 30
0

I get following response

{
  "data":"[{\"METER_READING\":\"25...}]"
}

The value of data is not an array; it is a string. That string is valid JSON which you could parse but why the service would do this is unclear.

So this should work:

JSONObject jObject = new JSONObject(jsonResultStr);
String parseMeAgain = jObject.optString("data");
McDowell
  • 107,573
  • 31
  • 204
  • 267
0

try using something like:

jsonResultStr = jsonResultStr.replace( "\\", "" ).replaceAll( "\"\\[", "[" ).replaceAll( "\\]\"", "]" );
JSONObject jObject = new JSONObject(jsonResultStr);
JSONArray jArray = jObject.optJSONArray("data");
injecteer
  • 20,038
  • 4
  • 45
  • 89
  • it gives the following exception Unrecognized backslash escape sequence in pattern near index 1: – user8938 Feb 13 '14 at 11:10
  • see updated `jsonResultStr.replaceAll( "\\", "" )` into `jsonResultStr.replace( "\\", "" );` – injecteer Feb 13 '14 at 11:23
  • Unterminated object at character 13 of {"data":"[{"METER_READING":"66","UTILITY_PLAN":"1","uname":"vinayak@triffort.com","kwh_usage":"11","meter_reading_date":"02-13-2014","ESID":"abc","METER_ID":"abc100"}]"} – user8938 Feb 13 '14 at 11:27
  • see the updated answer. I tried it with a groovy jsonslurper and it seems to work fine giving me the following output: `{data=[{UTILITY_PLAN=1, METER_READING=25, uname=vinayak@triffort.com, kwh_usage=9, meter_reading_date=02-13-2014, ESID=abc, METER_ID=abc100}]}` – injecteer Feb 13 '14 at 11:38
0

Your json should be like this

{
    "myarray": [
        {
            "METER_READING": "15",
            "UTILITY_PLAN": "1",
            "uname": "vinayak@triffort.com",
            "kwh_usage": "3",
            "meter_reading_date": "02-13-2014",
            "ESID": "abc",
            "METER_ID": "abc100"
        }
    ]
}

for network call

public String initializeConnection(String url) {
        String result = null;
        JSONObject jObj;


        try {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);
            if(client==null){Log.i("Clinet **************** ", "Client is null");}
            //post.setEntity(new UrlEncodedFormEntity(params));
            HttpResponse res = client.execute(post);
            result = inputStreamToString(res.getEntity().getContent()).toString();
            Log.d("Result from server:", result);
            jObj = new JSONObject(result.trim());           
        } catch (JSONException e1) {
            Log.e("Json Exception", e1.toString());
        } catch (ClientProtocolException e2) {
            Log.e("Client Protocol", e2.toString());
        } catch (IOException e3) {
            Log.e("Io exception", e3.toString());
        }
        return result;
    }

    private StringBuilder inputStreamToString(InputStream is) throws UnsupportedEncodingException {
        String rLine = "";
        StringBuilder answer = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);

        try {
            while ((rLine = rd.readLine()) != null) {
                answer.append(rLine);
            }
        }

        catch (IOException e) {
            e.printStackTrace();
        }
        return answer;
    }

to retrive from the json

ArrayList<String> params = new ArrayList<String>();
String result = networkCall.initializeConnection(url);

jObj = new JSONObject(result);

JSONArray jArray = jObj.optJSONArray("myarray");
params.add(jArray.optString(1));
params.add(jArray.optString(2));
params.add(jArray.optString(3));
params.add(jArray.optString(4));
params.add(jArray.optString(5));
params.add(jArray.optString(6));

now the data is stored in the params you can differentiate & store it as you want

Zeeshan Saiyed
  • 466
  • 4
  • 13
0

You can do this way :

JSONArray jsonArray = new JSONArray(result); // Pass your result here..
JSONObject jsonObject = jsonArray.getJSONObject(0);
String meterReading = jsonObject.getString("METER_READING");
String plan = jsonObject.getInt("UTILITY_PLAN");
String uname= jsonObject.getString("uname");
String meter_reading_date= jsonObject.getString("meter_reading_date");
String ESID= jsonObject.getString("ESID");
String METER_ID= jsonObject.getString("METER_ID");
Mehul Ranpara
  • 4,245
  • 2
  • 26
  • 39