I am getting String jsonObject in my controller. The structure is following:
{ "cats":
[
{
"name": "Smoky",
"age": 12,
"color": "gray"
},
{
"name": "Oscar",
"age": 3,
"color": "black"
},
{
"name": "Max",
"age": 4,
"color": "white"
}
]
}
I need to parse it into String[] jsonObjects or List<String> jsonObjects.
Using GSON I am trying to do it this way:
public static String[] toArray(String json) {
final String PARSING_ERROR = "Error while parsing json to string array";
try {
JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
String tableName = jsonObject.keySet().toArray()[0].toString();
JsonArray jsonArray = jsonObject.getAsJsonArray(tableName);
String[] strings = new String[jsonArray.size()];
for (int i = 0; i < jsonArray.size(); i++) {
String stringJson = jsonArray.get(i).toString();
strings[i] = stringJson;
}
return strings;
} catch (Exception e) {
System.err.println(PARSING_ERROR);
throw new DataException(PARSING_ERROR);
}
}
It works, but after parsing I recieve the following String:
{"name":"Smoky","age":12,"color":"gray"}
How can I get the String in the following format:
{
"name": "Smoky",
"age": 12,
"color": "gray"
}
Map