ObjectMappter read json string code example
Example 1: how to read file in java jacakson
try {
ObjectMapper mapper = new ObjectMapper();
Map<?, ?> map = mapper.readValue(Paths.get("book.json").toFile(), Map.class);
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 {
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(MyAwesomeClass.class, new MyAwesomeSerializer());
mapper.registerModule(module);
jsonNode = mapper.convertValue(myAwesomeObject, JsonNode.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();
}
}