I have the following JSON text. How can I parse it to get the values of pageName
, pagePic
, post_id
, etc.?
{ "pageInfo": { "pageName": "abc", "pagePic": "http://example.com/content.jpg" }, "posts": [ { "post_id": "123456789012_123456789012", "actor_id": "1234567890", "picOfPersonWhoPosted": "http://example.com/photo.jpg", "nameOfPersonWhoPosted": "Jane Doe", "message": "Sounds cool. Can't wait to see it!", "likesCount": "2", "comments": [], "timeOfPost": "1234567890" } ] }
Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.
java's built in JSON libraries are the quickets way to do so, but in my experience GSON is the best library for parsing a JSON into a POJO painlessly. There are many notorious java libraries in java: jackson, gson, org. json, genson, etc.
parse() The JSON. parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
The org.json library is easy to use.
Just remember (while casting or using methods like getJSONObject
and getJSONArray
) that in JSON notation
[ … ]
represents an array, so library will parse it to JSONArray
{ … }
represents an object, so library will parse it to JSONObject
Example code below:
import org.json.*; String jsonString = ... ; //assign your JSON String here JSONObject obj = new JSONObject(jsonString); String pageName = obj.getJSONObject("pageInfo").getString("pageName"); JSONArray arr = obj.getJSONArray("posts"); // notice that `"posts": [...]` for (int i = 0; i < arr.length(); i++) { String post_id = arr.getJSONObject(i).getString("post_id"); ...... }
You may find more examples from: Parse JSON in Java
Downloadable jar: http://mvnrepository.com/artifact/org.json/json
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With