user435062
user435062

Reputation: 133

Android: put NameValuePair data in JSONObject

I am trying to put NameValuePairdata to JSONObject. The NameValuePairdata has name as String and Value as JSONArray. Now when I tried to put this NameValuePairdata in a JSONObject, the jsonobject converts the JSONArray value to strings.

Please check below code for more details:

constructing NameValuePair:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

    nameValuePairs.add(new BasicNameValuePair("id", "1"));      

    JSONArray arr = new JSONArray();
    if(arrBean != null && arrBean.size() > 0) {
        for (Bean bean : arrBean) {
            JSONObject idsJsonObject = new JSONObject();
            try {
                idsJsonObject.put("min", bean.getMin());
                idsJsonObject.put("m1", bean.getMin());
                idsJsonObject.put("sec", bean.getSec());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            arr.put(idsJsonObject);
        }
    }
    nameValuePairs.add(new BasicNameValuePair("records", arr.toString()));

Constructing JSONObject to be send to HttpPost:

JSONObject JSONObjectData = new JSONObject();

    for (NameValuePair nameValuePair : nameValuePairs) {
        try {
            JSONObjectData.put(nameValuePair.getName(), nameValuePair.getValue());
        } catch (JSONException e) {

        }
    }

As shown above the JSONObjectData results into the following:

{"id":"1","records":"[{\"min\":\"610\",\"m1\":\"10\",\"sec\":\"\"},{\"min\":\"610\",\"m1\":\"10\",\"sec\":\"\"},{\"min\":\"610\",\"m1\":\"10\",\"sec\":\"\"},{\"min\":\"610\",\"m1\":\"10\",\"sec\":\"\"},{\"min\":\"610\",\"m1\":\"10\",\"sec\":\"\"},{\"min\":\"610\",\"m1\":\"10\",\"sec\":\"\"},{\"min\":\"610\",\"m1\":\"10\",\"sec\":\"\"},{\"min\":\"610\",\"m1\":\"10\",\"sec\":\"\"},{\"min\":\"610\",\"m1\":\"10\",\"sec\":\"\"},{\"min\":\"610\",\"m1\":\"10\",\"sec\":\"\"}]"}

You can see, it automatically appends \"value\" inside the array values. E.x. \"min\",\"m1\" etc...

Any body has any idea how to avoid appending these \"value\".

Please let me know. Thanks in advance.

Upvotes: 0

Views: 3922

Answers (1)

Alexander Sukharev
Alexander Sukharev

Reputation: 807

Both nameValuePair.getName() and nameValuePair.getValue() return strings, so they are added to your json as strings. You should pass a JSONArray object as a second parameter in JSONObjectData.put().

As BasicNameValuePair accept only string values, try to use HashMap<String, Object> instead or recreate the JSONArray from its String representation.

Upvotes: 2

Related Questions