You can use a library like gson.
Assuming you have model like this:
public class Products
{
private List<Product> products;
}
public class Product
{
private String name;
private String desc;
private String Quantity;
}
Easy way:
Add another attribute to Product model
private String matcode;
Now below code could be used:
Gson gson = new Gson();
String jsonOutput = "{\"products\": [{ \"name\" : \"ABC\" ,\"desc\" : \"abcde\", \"Quantity\": \"2\"}]}";
Products products = gson.fromJson(jsonOutput, Products.class);
System.out.println(products);
for(Product p : products.getProducts()){
p.setMatcode("001100");
}
System.out.println(gson.toJson(products));
Another longer path :
a. read the JSON response
b. convert to object ( which you should be already doing )
c. use gson to convert object to JsonElement as array
d. iterate and update the JsonObject as you require
e. convert the updated JsonElement to String output.
Working code below:
Gson gson = new Gson();
String jsonOutput = "{\"products\": [{ \"name\" : \"ABC\" ,\"desc\" : \"abcde\", \"Quantity\": \"2\"}]}";
Products products = gson.fromJson(jsonOutput, Products.class);
System.out.println(products);
JsonElement jsonElement = gson.toJsonTree(products);
JsonArray jsonArray = jsonElement.getAsJsonObject().get("products").getAsJsonArray();
for (JsonElement ele : jsonArray) {
JsonObject obj = ele.getAsJsonObject();
obj.addProperty("matcode", "001100");
}
String updatedJsonOutput = gson.toJson(jsonElement);
System.out.println("Updated json Object: " + updatedJsonOutput);