Please help me create jSonArray without keys. It should looks like:
"main" : ["one", "two", "three"]
I have tried it with empty key value:
private String generate(String value) {
Gson gson = new Gson();
JsonArray jsonArray = new JsonArray();
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("", value);
jsonArray.add(jsonObject);
return gson.toJson(jsonArray);
}
Result looks bad..
"main": "[
{\"\":\
"myString value\"}
]"
With this "json", for example, it would be impossible to read the array, because it has no key. Parsing a json like this one, you could get "bar" because it has a key ("foo_key"), but how could you get the array? The code you're using is already correct for a valid json.
The initial size parameter to the JsonArray constructor is defined as follows: An INTEGER variable that represents the size of the new JsonArray. Each element is initialized to the JSON null value. If this value is 0, the array is empty.
Create a JSON array by instantiating the JSONArray class and add, elements to the created array using the add() method of the JSONArray class.
When you are working with JSON data in Android, you would use JSONArray to parse JSON which starts with the array brackets. Arrays in JSON are used to organize a collection of related items (Which could be JSON objects). Show activity on this post. a JSONObject of {id: 1, name: 'B'} is equal to {name: 'B', id: 1} .
JsonObject obj = new JsonObject();
JsonArray array = new JsonArray();
array.add(new JsonPrimitive("one"));
array.add(new JsonPrimitive("two"));
array.add(new JsonPrimitive("three"));
obj.add("main", array);
You can do something like:
Gson gson = new Gson();
JsonArray array = new JsonArray();
array.add(new JsonPrimitive("one"));
array.add(new JsonPrimitive("two"));
array.add(new JsonPrimitive("three"));
JsonObject jsonObject = new JsonObject();
jsonObject.add("main", array);;
System.out.println(gson.toJson(jsonObject));
which outputs:
{"main":["one","two","three"]}
What you are trying to do is just to fill an array with primitive variables, to achieve that you have to change your code like this:
private String generate(String value) {
Gson gson = new Gson();
JsonArray jsonArray = new JsonArray();
jsonArray.add(new JsonPrimitive(value));
return gson.toJson(jsonArray);
}
Sample Code
JSONObject obj = new JSONObject();
JSONArray list = new JSONArray();
list.add("msg 1");
list.add("msg 2");
list.add("msg 3");
obj.put("", list);
You can use this to put an array without key.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With