javajsonparsingobject

Parse JSON object to string in java


I am a newbie to json parsing, I have grabbed a json string from a request and now I need to parse it with java. I'm using simple-lib for this. But I'm really stuck as I'm not familiar with it. I need to extract following data

I used following java code for that but it's not giving me the result I need, please someone help me...

    JSONParser parser = new JSONParser();

    try {
        Object obj = parser.parse(new FileReader("test.json"));

        JSONObject jsonObject = (JSONObject) obj;

        JSONArray msg = (JSONArray) jsonObject.get("content");
        Iterator<String> iterator = msg.iterator();
        while(iterator.hasNext()) {
            System.out.println(iterator.next());

        }

Sample JSON

{
    "status": 200,
    "message": "ok",
    "timestamp": "2014-05-22T14:29:56.824+03:00",
    "pagesCount": 1,
    "version": "1.1",
    "pages": [
        {
            "number": 100,
            "subpages": [
                {
                    "number": 1,
                    "timestamp": "2014-05-22T13:41:41.116+03:00",
                    "content": "text"
                },

Solution

  • Something like this perhaps?

    JSONParser parser = new JSONParser();
    
    JSONObject jsonObject = (JSONObject) parser.parse(new FileReader("test.json"));
    JSONArray pages = (JSONArray) jsonObject.get("pages");
    if (pages != null) {
        for (Object p : pages) {
            JSONObject page = (JSONObject) p;
            JSONArray subPages = (JSONArray) page.get("subpages");
            if  (subPages != null) {
                for (Object sp : subPages) {
                    JSONObject subPage = (JSONObject) sp;
                    System.err.println(subPage.get("content"));
                }
            }
        }
    }