readvalue() of objectmapper code example

Example 1: how to read file in java jacakson

try {
    // create object mapper instance
    ObjectMapper mapper = new ObjectMapper();

    // convert JSON file to map
    Map<?, ?> map = mapper.readValue(Paths.get("book.json").toFile(), Map.class);

    // print map entries
    for (Map.Entry<?, ?> entry : map.entrySet()) {
        System.out.println(entry.getKey() + "=" + entry.getValue());
    }

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

Example 2: java json serializer

public class someClass {
//your lcode and logic...
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(MyAwesomeClass.class, new MyAwesomeSerializer());
mapper.registerModule(module);

jsonNode = mapper.convertValue(myAwesomeObject, JsonNode.class);
//... your code and logic
}
 
//serializer class
public class MyAwesomeSerializer extends StdSerializer<MyAwesomeClass> {

    public MyAwesomeSerializer() {
        super(MyAwesomeClass.class);
    }

    @Override
    public void serialize(MyAwesomeClass myAwesomeClass, JsonGenerator jgen, SerializerProvider provider) throws IOException {
        ObjectMapper mapper = new ObjectMapper();

        jgen.writeStartObject();
        jgen.writeStringField("name", myAwesomeClass.getName());
        jgen.writeStringField("age", myAwesomeClass.getAge());

          jgen.writeArrayFieldStart("hobbies");
          for (Hobby hobby : myAwesomeClass.getHobbies()) {
              jgen.writeObject(mapper.convertValue(hobby, JsonNode.class));
          }
          jgen.writeEndArray();
      
        jgen.writeEndObject();
    }

}

Tags:

Java Example