0

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?

3
  • Are you asking how to convert the top JSON to be like the bottom JSON. Or do you just need to convert the value to an int? Commented Aug 3, 2018 at 19:02
  • Top to be like the bottom Commented Aug 3, 2018 at 19:04
  • why you want to do that? even though if you want to do it I would recommend not to do that. Better to parse quantity as integer wherever is required or convert your json into a pojo. json2Pojo Commented Aug 3, 2018 at 19:12

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

Since it's a JSONArray I need to do it like: array.getJSONArray(i).Quantity . But the problem is that I get an unresolved symbol at Quantity....
You are correct. My bad. I updated my post. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.