2

I am new to JSON and I am learning using the json.simple library. I can't figure out how to access the values in the nested objects or arrays. Here is a piece of the JSON file that I am working with:

{
   metrics: {
      steps: {
         min: 0,
         max: 140,
         sum: 1161,
         summary: {
            max_steps_per_minute: null,
            min_steps_per_minute: null
         },
         values: [
            0,
            0,
            0,
            0,
            0,
           13,
            0,
            0,
            0,
1
  • I recommend you gson library. It's very useful with json having arrays. Commented Jan 23, 2014 at 20:40

1 Answer 1

3

Of course as soon as I asked this I figured it out. In case someone else needs this information here is some of the code to show what I did:

public void fileDecode()
    {
        JSONParser parser = new JSONParser();

        try
        {
            FileReader file = new FileReader("C:\\JSONData\\test.json");
            Object obj = parser.parse(file);
            JSONObject jsonObject = (JSONObject)obj;
            JSONObject metrics = (JSONObject)jsonObject.get("metrics");
            JSONObject steps = (JSONObject)metrics.get("steps");
            JSONArray values = (JSONArray)steps.get("values");

            Iterator<Integer> iterator = values.iterator();
            while (iterator.hasNext())
            {
                System.out.println(iterator.next());
            }
            System.out.println(steps.get("min"));
            System.out.println(metrics.get("steps"));
            System.out.println(jsonObject.get("metrics"));

            file.close();
        }

        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }

    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.