Java 如何使用Gson将列表转换为json?

Java 如何使用Gson将列表转换为json?,java,android,json,Java,Android,Json,这里我需要像这样的json格式发送到服务器我怎么能做到这一点我已经尝试了很多方法,但我无法得到这里是我的格式: {"accountModel":[ { "AddressLine1": "purasai", "AddressLine2": "otteri", "AddressLine3": "t nagar", "CompanyGroup": "yogangroups", "CompanyName": "yogan inc", "IsIndivi

这里我需要像这样的json格式发送到服务器我怎么能做到这一点我已经尝试了很多方法,但我无法得到这里是我的格式:

{"accountModel":[
  {
    "AddressLine1": "purasai",
    "AddressLine2": "otteri",
    "AddressLine3": "t nagar",
    "CompanyGroup": "yogangroups",
    "CompanyName": "yogan inc",
    "IsIndividual": 1,
    "IsMulitLocation": 1,
    "LandLine1": "landline1",
    "LandLine2": "Landline2",
    "PinCode": "pincode",
    "WebSiteContactEmailID": "vbbb",
    "WebsiteURL": "ghb",
    "company_name_id": 68,
    "AccountManagerID": 185,
    "CityID": 165,
    "IndustryID": 4,
    "RegionID": 24,
    "StateID": 129
  },
  {
    "AddressLine1": "yoh",
    "AddressLine2": "f",
    "AddressLine3": "",
    "CompanyGroup": "uo",
    "CompanyName": "vv",
    "IsIndividual": 1,
    "IsMulitLocation": 1,
    "LandLine1": "landline1",
    "LandLine2": "Landline2",
    "PinCode": "pincode",
    "WebSiteContactEmailID": "yg",
    "WebsiteURL": "ff",
    "company_name_id": 10,
    "AccountManagerID": 185,
    "CityID": 165,
    "IndustryID": 5,
    "RegionID": 24,
    "StateID": 126
  }
]}
我怎样才能做到这一点!!我使用过Gson库:

Gson gson=new Gson();
        String Json=gson.toJson(listobj);
        JSONObject jobj=new JSONObject();
        try {
            jobj.put("accountModel",Json.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

但我无法获得所需的格式

用这个我想它能帮你

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.google.code.gson:gson:2.6.1'
}

使用此代码构造json对象

Gson gson = new GsonBuilder().create();
        JsonArray myCustomArray = gson.toJsonTree(listobj).getAsJsonArray();
        JsonObject jsonObject = new JsonObject();
        jsonObject.add("accountModel", myCustomArray);
然后使用下面的代码将其转换为jsonString。希望这能解决你的问题

jsonObject.toString()

你得到了什么输出?假设listobj是一个表示json数组中项目的对象列表,上面的代码应该为您提供一个有效的json对象,该对象带有一个值为json数组的单字段(accountModel)