简体   繁体   English

从带有或不带有JSONObject的json字符串中提取数据

[英]Extract data from json string with or without JSONObject

I've got the following json code stored in a java String: 我在Java字符串中存储了以下json代码:

String str = {"posts":[{"key":"key1","value":"x"},{"key":"key2","value":"0"},{"key":"key3","value":"y"}]}

Is there a way to extract the values from the string using JSONObject or should I use the old school method: 有没有一种方法可以使用JSONObject从字符串中提取值,还是应该使用旧的学校方法:

 String[] parts = str.split("\"");

In my case the values are stored in the array at the positions: parts[9] , parts[17] and parts[25] . 在我的情况下,值存储在数组中的位置: parts[9]parts[17]parts[25] It works well so far, but I wonder if I could use JSONObject for that task? 到目前为止,它运行良好,但是我想知道是否可以将JSONObject用于该任务吗?

Use Gson library provided by google if you are using Java 如果您使用的是Java,请使用Google提供的Gson库

https://github.com/google/gson https://github.com/google/gson

Here you can convert your java to Json and Json back to java objects seamlessly. 在这里,您可以将Java转换为Json,然后将Json无缝转换回Java对象。

Using JSONObject (from the org.json package, JSON-java ), you can easily extract values. 使用JSONObject (来自org.jsonJSON-java ),您可以轻松提取值。

final JSONObject jsonObject = new JSONObject(str);
final JSONArray posts = jsonObject.getJSONArray("posts");
final Collection<String> values = new ArrayList<>(posts.length());

for (int i = 0; i < posts.length(); i++) {
    final JSONObject post = posts.getJSONObject(i);
    values.add(post.getString("value"));
}

// values = [x, 0, y]

I'd absolutely avoid any kind of manual String manipulation. 绝对会避免任何手动的String操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM