无法遍历JSONArray

时间:2014-01-29 06:02:39

标签: java json eclipse io arrays

我有一个JSON文件,如下所示。

[
    {
        "_type": "ArticleItem",
        "body": "But under Obamacare, many can find plans in the $50 to $70 range, he said.",
        "title": "Who's signing up for Obamacare? - Jan. 13, 2014",
        "source": "money.cnn.com",
        "last_crawl_date": "2014-01-14",
        "url": "http://money.cnn.com/2014/01/13/news/economy/obamacare-enrollment/index.html"
    },
    {
        "_type": "ArticleItem",
        "body": "debut on January 25 at the Daytona International Speedway.",
        "title": "GM reveals 625-horsepower Corvette Z06 - Jan. 13, 2014",
        "source": "money.cnn.com",
        "last_crawl_date": "2014-01-14",
        "url": "http://money.cnn.com/2014/01/13/autos/chevrolet-corvette-z06/index.html"
    }
]

这只是一个样本,原始最终包含数百万条记录。我需要遍历这个,并打印标题和正文。这就是我所做的。

 public void createHash()
    {
        AmazonS3 s3 = new AmazonS3Client(new ClasspathPropertiesFileCredentialsProvider());
        Region usWest2 = Region.getRegion(Regions.US_EAST_1);
        s3.setRegion(usWest2);

        strBuffer = new StringBuffer("");

        try
        {
            //List all the Buckets
            List<Bucket>buckets = s3.listBuckets();

            for(int i=0;i<buckets.size();i++)
            {
                System.out.println("- "+(buckets.get(i)).getName());
            }


            //Downloading the Object
            System.out.println("Downloading Object");
            S3Object s3Object = s3.getObject(new GetObjectRequest("JsonBucket", "Articles_4.json"));
            System.out.println("Content-Type: "  + s3Object.getObjectMetadata().getContentType());


            //Read the JSON File
            BufferedReader reader = new BufferedReader(new InputStreamReader(s3Object.getObjectContent()));
            while (true) {
                String line = reader.readLine();
                if (line == null) break;

               // System.out.println("    " + line);
                strBuffer.append(line);
                //System.out.println(line);
            }

            JSONTokener jTokener = new JSONTokener(strBuffer.toString());
            JSONArray jsonArray = new JSONArray(jTokener);



            for(int i=0;i<jsonArray.length();i++)
            {
                JSONObject insideLoopObject = jsonArray.getJSONObject(i);

                System.out.println("Printing JSON Title.........");
                System.out.println(insideLoopObject.getString("title"));
                System.out.println("Printing Body.........");
                System.out.println(insideLoopObject.getString("body"));
            }


        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

不幸的是,它的作用是,一次又一次地打印相同的JSON对象,它不是迭代的。我知道我提取JSON的方式是正确的,因为我可以逐个手动打印,就像这样。

JSONObject jsonObject = jsonArray.getJSONObject(0);
JSONObject jsonObject1 = jsonArray.getJSONObject(1);

那么,我的代码出了什么问题?请帮助。

0 个答案:

没有答案