Reputation: 110
I want to create a JSON string like this:
[{"addon_id":2,"addon_rate":1550},{"addon_id":3, "addon_rate":300}]
Is this possible? How?
My code as it stands:
String formattedString = BookingDetailsCartAdapter.addones_id.toString().replace("[", "").replace("]", "").trim();
String formattedString1 = BookingDetailsCartAdapter.addones_rate.toString().replace("[", "").replace("]", "").trim();
myjson="[{\"addon_id\":\""+formattedString+"\",\"addon_rate\":\""+formattedString1+"\"}]";
Upvotes: 3
Views: 4271
Reputation: 17131
You can use GSON
Add in Gradle file
compile 'com.google.code.gson:gson:2.8.1'
public class Addon{
public int addon_id;
public int addon_rate;
}
Addon addon = new Addon ();
addon.addon_id=2;
addon.addon_id=1550;
Gson gson = new Gson();
String json = gson.toJson(addon); //
//--- For array
List<Addon > objList = new ArrayList<Addon >();
objList.add(new Addon (0, 1550));
objList.add(new Addon (1, 1552));
objList.add(new Addon (2, 1553));
String json = new Gson().toJson(objList);
System.out.println(json);
http://www.javacreed.com/simple-gson-example/
Upvotes: 4
Reputation: 8106
Your JSON means that it's an array which contains two objects with the keys addon_id and addon_rate. Both accept a number/integer as value. First you need to create a JSONArray which holds several JSONObjects. Then you have to create the JSONObjects which set your keys and values. After this you need to add those objects to your array. Your jsonArray contains the string above as soon as you print/toString() it
JSONArray jsonArray = new JSONArray();
JSONObject jsonObjOne = new JSONObject();
jsonObjOne.put("addon_id", 2);
jsonObjOne.put("addon_rate", 1550);
JSONObject jsonObjTwo = new JSONObject();
jsonObjTwo.put("addon_id", 3);
jsonObjTwo.put("addon_rate", 300);
jsonArray.put(jsonObjOne);
jsonArray.put(jsonObjTwo);
Upvotes: 4