How to create a JSONArray with GSON

前端 未结 3 700
暖寄归人
暖寄归人 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

提交回复
热议问题