user3369592
user3369592

Reputation: 1447

parse the json file with mutiple objects using Jackson

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

    }

Upvotes: 1

Views: 1598

Answers (2)

T.Tony
T.Tony

Reputation: 515

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 :)

Upvotes: 1

Ravindra Devadiga
Ravindra Devadiga

Reputation: 692

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

Upvotes: 2

Related Questions