1

My json file contains multiple objects :

[
{
      "name":"Move",
      "$$hashKey":"object:79",
      "time":11.32818,
      "endTime":18.615535
   },
   {
      "name":"First Red Flash",
      "$$hashKey":"object:77",
      "time":15.749153
   },
   {
      "name":"Pills",
      "subEventTypes":[
         "pull down bottle",
         "unscrew lid",
         "dump pills out",
         "screw lid on",
         "put bottle away"
      ],
      "$$hashKey":"object:82",
      "time":25.130175,
      "subEventSplits":[
         26.092057,
         27.425881,
         31.841594,
         34.268093
      ],
      "endTime":36.234827
   }

 }

Is there a way to parse this Json file using Jackson? Or are there any other libraries available that allow me to parse a Json file in this format? Here is my code so far :

    File file = new File("data.json");
    JsonFactory jsonFactory = new JsonFactory();
    JsonParser parser = jsonFactory.createJsonParser(file);
    while(parser.nextToken()!=JsonToken.END_OBJECT)
    {
            //how to read each token

    }
3
  • 1
    Jackson can parse any JSON. Commented Oct 24, 2016 at 4:44
  • @4castle provided, it is syntatically correct. The file in the post is missing a closing ]. Commented Oct 24, 2016 at 4:54
  • @user3369592 go with GSON Library. with help of this : github.com/google/gson Commented Oct 24, 2016 at 5:05

2 Answers 2

2

Jackson should parse the JSON file which you have mentioned. Create a classes as shown below

Class Holder {
    String name;
    List<String> subEventTypes = new ArrayList<>();
    String $$hashKey;
    Double time;
    List<Double> subEventSplits = new ArrayList<>()
    DOuble endTime;
}

Class MapperClass{
    List<Holder> list = new ArrayList<>();
}

Parse it as shown below

ObjectMapper mapper = new ObjectMapper();

//JSON from file to Object
MapperClass values = mapper.readValue(new File("c:\\values.json"), MapperClass.class);

Refer this link for more details

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

2 Comments

I have updated my question. May you take a look at it.
This link gives solutions for your updated requirement
1

You can use the Tree Model, it's like

ObjectMapper m = new ObjectMapper();
JsonNode rootNode = m.readTree(new File("data.json"));
Iterator<JsonNode> it = rootNode.getElements();

while(it.hasNext()) {
    System.out.println("element : " + it.next().toString());
}

then you will see what you want :)

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.