我得到String jsonObject
在我的 Controller 中。结构如下:
{ "cats":
[
{
"name": "Smoky",
"age": 12,
"color": "gray"
},
{
"name": "Oscar",
"age": 3,
"color": "black"
},
{
"name": "Max",
"age": 4,
"color": "white"
}
]
}
我需要将其解析为 String[] jsonObjects
或List<String> jsonObjects
.
使用 GSON 我尝试这样做:
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);
}
}
它有效,但解析后我收到以下字符串:
{"name":"Smoky","age":12,"color":"gray"}
如何获取以下格式的字符串:
{
"name": "Smoky",
"age": 12,
"color": "gray"
}
最佳答案
抱歉,对于 PO 的问题,这不是正确的答案,但可能对其他用户有帮助......想要使用 GSON 来(漂亮)序列化对象,所以 String jsonOutput = gson.toJson(someObject);
你“只是”需要:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(jsonObject);
See here .
关于java - 如何从包含未经修改的数组的 String JSON 中获取 java 中 JSON 对象的 String[] 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54620214/