objectmapper jackson file to object 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 deserializer
private Car parseCar(JsonNode node) {
Car car;
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule().addDeserializer(Car.class, new CarDeserializer());
mapper.registerModule(module);
organization = mapper.convertValue(node, Car.class);
return car;
}
public class CarDeserializer extends StdDeserializer<Car> {
public CarDeserializer() {
super(Car.class);
}
@Override
public Car deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JodaModule());
Car car = new Car();
car.setName(getValueAsText(root, "carName"));
car.setDoorCount(getValueAsInt(root,"doorCount"));
car.setColor(getValueAsText(root,"color"));
car.setType(getValueAsText(root,"type"));
return car;
}
}
Example 3: convert json to object jackson
ObjectMapper objectMapper = new ObjectMapper();
String carJson =
"{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";
try {
Car car = objectMapper.readValue(carJson, Car.class);
System.out.println("car brand = " + car.getBrand());
System.out.println("car doors = " + car.getDoors());
} catch (IOException e) {
e.printStackTrace();
}