Android Json Object put a Array JSON without key

523 Views Asked by At

i need to create a json with estructure

    {
      "label": "any description",
      "location":[25.7752965,-100.2636682]
    }

Json Object with array without key,value (location),

I try with

String[] _location = new String[2];
_location[0] = String.valueOf(latLng.latitude);
_location[1] = String.valueOf(latLng.longitude);

JSONObject params = new JSONObject();
params.put("location",_location);
params.put("label",_label);

Another try use:

       JsonObject obj = new JsonObject();
       JsonArray array_location = new JsonArray();
       array_location.add(currentLocation.latitude);
       array_location.add(currentLocation.longitude);
       JSONObject params = new JSONObject();
       params.put("location",_location);
       params.put("label",_label);

But, the result give me a json with string values...when i need a key "location" with value as Array double

 {
     "label": "any description",
     "location":"[25.7752965,-100.2636682]"
  }
1

There are 1 best solutions below

0
Son Truong On BEST ANSWER

Solution

JSONObject params = new JSONObject();
params.put("label", "any description");

JSONArray locationJsonArray = new JSONArray();
locationJsonArray.put(25.775296); // Replace by your latitude
locationJsonArray.put(-100.2636682); // Replace by your longitude
params.put("location", locationJsonArray);

// For debug purpose
Log.i("DEBUG", params.toString(4));

Result

{
  "label": "any description",
  "location": [
    25.775296,
    -100.2636682
  ]
}