How to create a JSONArray with GSON

前端 未结 3 606
暖寄归人
暖寄归人 2021-01-15 17:42

Hi in my project i need to create a JSONArray type with the GSON class

    {
  \"message\": [
    \"msg 1\",
    \"msg 2\",
    \"msg 3\"
  ],
  \"asec\": [         


        
相关标签:
3条回答
  • 2021-01-15 18:30

    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

    0 讨论(0)
  • 2021-01-15 18:34

    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

    0 讨论(0)
  • 2021-01-15 18:35
    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));
    
    0 讨论(0)
提交回复
热议问题