如何从包含未经修改的数组的String JSON获取Java中的JSON对象的String []数组

时间:2019-02-10 19:34:44

标签: java json

我的控制器中出现String jsonObject。结构如下:

{ "cats":
    [
        {
  "name": "Smoky",
  "age": 12,
  "color": "gray"
},
        {
  "name": "Oscar",
  "age": 3,
  "color": "black"
},
       {
  "name": "Max",
  "age": 4,
  "color": "white"
}
    ]
}

我需要将其解析为String[] jsonObjectsList<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"
}

2 个答案:

答案 0 :(得分:1)

对不起,这不是PO问题的正确答案,但可能对其他想要使用GSON(漂亮)序列化对象的用户有所帮助,因此String jsonOutput = gson.toJson(someObject);

您“只是”需要:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(jsonObject);

See here

答案 1 :(得分:0)

在您的情况下,您仅使用GSON来从JSON 读取(反序列化):

JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);

对于结果String[]及其输出,您的程序负责!

...而且,如果您不想重新发明轮子,例如采用“漂亮”格式且由于GSON已“在船上”,您可以执行以下操作:

public static String[] toArray(String json) {
    final String PARSING_ERROR = "Error while parsing json to string array";
    // one for toJson() (only)
    final Gson gsonPretty = new GsonBuilder().setPrettyPrinting().create();
    // one for fromJson (demo only)
    final Gson gsonUgly = new Gson();
    try {
        JsonObject jsonObject = gsonUgly.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++) {
            // de-serialize & then pretty serialize each "cat".
            String catJson = jsonArray.get(i).toString();
            JsonObject catObj = gsonUgly.fromJson(catJson, JsonObject.class);
            strings[i] = gsonPretty.toJson(catObj);
        }
        return strings;
    } catch (Exception e) {
        System.err.println(PARSING_ERROR);
        throw new DataException(PARSING_ERROR);
    }
}