How do I parse JSON data in Java?

Asked 2 years ago, Updated 2 years ago, 80 views

For the following JSON text, I would like to parse data for pageName, pagePic, post_id.

What should I do?

{
   "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"
         }
    ]
}

java json parsing

2022-09-21 21:12

1 Answers

The org.json library makes it easy to implement. The example code is as follows:

import org.json.*;


JSONObject obj = new JSONObject(" .... ");
String pageName = obj.getJSONObject("pageInfo").getString("pageName");

JSONArray arr = obj.getJSONArray("posts");
for (int i = 0; i < arr.length(); i++)
{
    String post_id = arr.getJSONObject(i).getString("post_id");
    ......
}

For more examples, see Parse JSON in Java

Download jar file: http://mvnrepository.com/artifact/org.json/json


2022-09-21 21:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.