Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse JSON in Java

Tags:

java

json

parsing

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"              }         ]     } 
like image 970
Muhammad Maqsoodur Rehman Avatar asked Apr 07 '10 09:04

Muhammad Maqsoodur Rehman


People also ask

How do I parse a JSON file?

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.

Can Java read JSON?

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.

What is JSON parse () method?

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.


1 Answers

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

like image 66
user1931858 Avatar answered Sep 20 '22 16:09

user1931858