2016-02-26 58 views
0

在這裏,我需要這樣的JSON格式發送到服務器,我怎麼能做到這一點我已經試過很多辦法,但我不能讓這是我的格式:如何使用Gson將列表轉換爲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(); 
     } 

但我無法得到所需的格式!

回答

-4

使用這個我認爲它可以幫助你

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

使用此代碼構造JSON對象。

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

然後使用下面的代碼將它轉換成jsonString。希望這會解決你的問題。

jsonObject.toString() 
-1

你會得到什麼輸出?假設listobj是表示json數組中項目的對象列表,上面的代碼應該爲您提供一個有效的json對象,其中包含一個sigle字段(accountModel),其值是一個json數組。

相關問題