I'm assuming you have 2 arrays one containing and product_id and the other containing the values and both of these are in correct order.
I would create my own java object (POJO) that had two fields product_id
and name
then take your two arrays and create one array (or list) of POJOs each POJO containing the product_id and name. Then I would just use Jackson or Gson to create my JSON.
These libraries give you a JSON representation of a Java Objects, so in this case you will have to make sure that you have a list or even an array of objects which contain your product_id
and name
.
If you insist on doing it the hard-way (or no external library way), then I would create a template String and repeatedly call replace on it and add it to a StringBuffer. The StringBuffer is important if the string can be very large. Something like:
String template = "{\"product_id\":\"productId\",\"name\":\"productName\"}";
StringBuffer result = new StringBuffer("[");
for(int i=0; i<myProductArray.length; i++){
String temp = template.replace("productId",myProductArray[i]);
temp = temp.replace("productName",myNameArray[i]);
if(result.length() > 1)
result.append(",");
result.append(temp);
}
result.append("]");
return result.toString();
If you can replace the template
String
with a StringBuffer
and manipulate that directly, it'll make a ton of difference performance wise for large Strings.
Regards,