1

Here i need json format like this to send to server how can i do this i have tried so many way but i could not get here is my format:

{"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
  }
]}

How can i achieve this !! i have used Gson library:

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

But i could not get Desired Format !!

Yog
  • 137
  • 2
  • 14

3 Answers3

3

Use this code construct json object.

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

then use the below code to convert it into jsonString. Hopefully this will solve your problem.

jsonObject.toString()
Hunain
  • 385
  • 5
  • 15
-1

what what output are you getting? assuming listobj is a list of objects representing the items in the json array, the code above should give you a valid json object with a sigle field (accountModel) whose value is a json array.

araoko
  • 93
  • 2
  • 6
-4

use this I think it can help you

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