bond
bond

Reputation: 718

Convert JSONArray string value into int value

I need to convert the value from key "Quantity" into a int.

Basically I have this:

[{"Code":"NV","Quantity":"333"},{"Code":"NV","Quantity":"333"}]

Need to convert to this:

[{"Code":"NV","Quantity":333},{"Codigo":"NV","Quantity":333}]

How can I do it?

Upvotes: 0

Views: 1186

Answers (2)

Varad Mondkar
Varad Mondkar

Reputation: 1561

Assuming your json data in string and setting it in data string

String data = "[{\"Code\":\"NV\",\"Quantity\":\"333\"},{\"Code\":\"NV\",\"Quantity\":\"333\"}]";

try {
    JSONArray jsonArray = new JSONArray(data);
    Log.d(TAG, "Old JSONArray: " + jsonArray); // [{"Code":"NV","Quantity":"333"},{"Code":"NV","Quantity":"333"}]

    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonObject = (JSONObject) jsonArray.get(i);
        int quantityValue = Integer.parseInt(jsonObject.getString("Quantity"));
        jsonObject.put("Quantity", quantityValue);
    }
    Log.d(TAG, "New JSONArray: " + jsonArray); // [{"Code":"NV","Quantity":333},{"Code":"NV","Quantity":333}]

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

What I am doing here is just replacing old Quantity string value with int value by using Integer.parseInt()

Upvotes: 1

James
James

Reputation: 1972

Please try the following:

for(int i = 0; i < array.length(); i++){
    JSONObject object = array.getJSONObject(i); 
    object.put("Quantity", Integer.parseInt(object.getString("Quantity")));
}

You will need to replace array with the name of your array.

Upvotes: 0

Related Questions