Hi in my project i need to create a JSONArray type with the GSON class
{
\"message\": [
\"msg 1\",
\"msg 2\",
\"msg 3\"
],
\"asec\": [
Try below code to create JsonObject you desired.
String[] msgArray = new String[]{"msg 1", "msg 2", "msg 3"};
String[] asecArray = new String[]{"asec 1", "asec 2", "asec 3"};
Gson gson = new Gson();
JsonObject obj = new JsonObject(); //Json Object
obj.add("message", gson.toJsonTree(msgArray));
obj.add("asec", gson.toJsonTree(asecArray));
String jsonString = gson.toJson(obj); //Json String
Refer Gson documentation for more details
the class:
public class JsonStructure{
public String[] message;
public String[] asec;
}
using it:
JsonStructure json = new JsonStructure();
json.message = new String[]{"msg 1", "msg 2", "msg 3"};
json.asec = new String[]{"asec 1", "asec 2", "asec 3"};
Gson gson = new Gson();
String output = gson.toJson(json);
//convert from string
JsonStructure fromString = gson.fromJson(output, JsonStructure.class);
For more details on Google's gson please take a look at https://sites.google.com/site/gson/gson-user-guide
public class ArrayBean {
ArrayList<String> message = new ArrayList<String>();
ArrayList<String> asec = new ArrayList<String>();
}
create bean class above arraybean, then u can add the values on your main class and print the output.
Gson gson = new Gson();
ArrayBean arrayBean = new ArrayBean();
arrayBean.message.add("msg 1");
arrayBean.message.add("msg 2");
arrayBean.message.add("msg 3");
arrayBean.asec.add("asec 1");
arrayBean.asec.add("asec 2");
arrayBean.asec.add("asec 3");
Log.d("rvg",""+gson.toJson(arrayBean));