我将如何获取所有“名称”值并将其转换为字符串?
因此,例如,如果我要执行以下操作:

System.out.println(value[1]);


它将打印出name1
这是我到目前为止的内容:

JSON:

[
    {
        "name":"name1"
    },
    {
        "name":"name2",
        "changedToAt":1470659096000
    },
    {
        "name":"name3",
        "changedToAt":1473435817000
    }
]


Java代码:

try {
    String UUID = p.getUniqueId().toString();
    String slimUUID = UUID.replace("-", "");
    InputStream in = new URL("https://api.mojang.com/user/profiles/" + slimUUID + "/names").openStream();

    String json = IOUtils.toString(in);
    IOUtils.closeQuietly(in);

    try {
        JSONParser parser = new JSONParser();
        JSONObject jsonparse = (JSONObject) parser.parse(json);
        //get "name" values and turn into String
    } catch (ParseException e) {
        System.out.println(e.getMessage());
    }

    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
}

最佳答案

您需要遍历数组并将所有name值累加到字符串数组中。

因此,以下是工作源代码:

JsonArray jsonObject = new JsonParser()
        .parse(json)
        .getAsJsonArray();

List<String> names = new ArrayList<>();
for (JsonElement jsonElement : jsonObject) {
    names.add(jsonElement.getAsJsonObject().get("name").getAsString());
}

//now you can use as you wish, by index
System.out.println(names.get(1));//returns "name2"

10-08 14:44