I've got the following json code stored in a java String:
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:
String[] parts = str.split("\"");
In my case the values are stored in the array at the positions: parts[9]
, parts[17]
and parts[25]
. It works well so far, but I wonder if I could use JSONObject
for that task?
Use Gson library provided by google if you are using Java
https://github.com/google/gson
Here you can convert your java to Json and Json back to java objects seamlessly.
Using JSONObject
(from the org.json
package, JSON-java ), you can easily extract values.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.