Java - 获取多个JSON值并转换为String

时间:2017-06-10 19:30:50

标签: java json

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

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());
    }
}

3 个答案:

答案 0 :(得分:2)

您需要遍历数组并将所有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"

答案 1 :(得分:1)

使用评论和Java 8 Stream API中的URL我已经构建了这个主要方法:

    public static void main(final String[] args) throws ParseException, MalformedURLException, IOException {
    final String url = "https://api.mojang.com/user/profiles/c8570e47605948d3a3cbe3ec3a681cc0/names";
    final InputStream in = new URL(url).openStream();
    final String json = IOUtils.toString(in);
    IOUtils.closeQuietly(in);
    final JSONParser parser = new JSONParser();
    final JSONArray jsonparse = (JSONArray) parser.parse(json);
    System.out.println(jsonparse);
    System.out.println();
    final List<String> names = (ArrayList<String>) jsonparse.stream().map((obj) -> {
        final JSONObject object = (JSONObject) obj;
        return (String) object.getOrDefault("name", "");
    }).peek(System.out::println).collect(Collectors.toList());
}

答案 2 :(得分:0)

试试我的图书馆:AbacusUtil。以上所有内容均可替换为:

List<Map<String, Object>> resp = HttpClient.of("https://api.mojang.com/user/profiles/" + slimUUID + "/names").get(List.class);
List<String> names = resp.stream().map(m -> (String) (m.get("name"))).collect(Collectors.toList());

顺便说一句,如果slimUUID等于:UUID.randomUUID().toString().replaceAll("-", "")。它被简化了:

List<Map<String, Object>> resp = HttpClient.of("https://api.mojang.com/user/profiles/" + N.guid()+ "/names").get(List.class);
List<String> names = resp.stream().map(m -> (String) (m.get("name"))).collect(Collectors.toList());