【问题标题】:How to convert list to json using Gson? [duplicate]如何使用 Gson 将列表转换为 json? [复制]
【发布时间】:2016-02-26 10:57:59
【问题描述】:

这里我需要像这样的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();
        }

但我无法获得所需的格式!

【问题讨论】:

    标签: java android json


    【解决方案1】:

    使用此代码构造 json 对象。

    Gson gson = new GsonBuilder().create();
            JsonArray myCustomArray = gson.toJsonTree(listobj).getAsJsonArray();
            JsonObject jsonObject = new JsonObject();
            jsonObject.add("accountModel", myCustomArray);
    

    然后使用下面的代码将其转换为 jsonString。希望这能解决您的问题。

    jsonObject.toString()
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        使用这个我认为它可以帮助你

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-02-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多