ObjectMapper

它是线程安全的,所以建议使用它时,作为单例使用:

private static final ObjectMapper mapper = new ObjectMapper();

Quick Parsing

String jsonString = "{\"k1\":\"v1\",\"k2\":\"v2\"}";
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree(jsonString);
assertNotNull(actualObj);

Convert JSON to Java Map

 JsonFactory factory = new JsonFactory();
 ObjectMapper mapper = new ObjectMapper(factory);
 File from = new File("albumnList.txt");
 TypeReference<HashMap<String,Object>> typeRef = new TypeReference<HashMap<String,Object>>() {};
 HashMap<String,Object> o = mapper.readValue(from, typeRef);
 System.out.println("Got " + o); 

Convert JSON to Java List

String value = "{json string}"
ObjectMapper om = new ObjectMapper();
List<Integer> agentList = om.readValue(value, om.getTypeFactory().constructCollectionType(List.class, Integer.class));

Convert JSON to Java object

ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(new File("c:\\user.json"), User.class);

Convert JavaObject to JSON String

mapper.writeValue(new File("c:\\user.json"), user);
 // display to console
 System.out.println(mapper.writeValueAsString(user));

Low Level Parsing

String jsonString = "{\"k1\":\"v1\",\"k2\":\"v2\"}";

ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getFactory();
JsonParser parser = factory.createParser(jsonString);
JsonNode actualObj = mapper.readTree(parser);
 assertNotNull(actualObj);

Use jsonNode

String jsonString = "{\"k1\":\"v1\",\"k2\":\"v2\"}";
ObjectMapper mapper = new ObjectMapper();
 JsonNode actualObj = mapper.readTree(jsonString);

 // When
 JsonNode jsonNode1 = actualObj.get("k1");
 assertThat(jsonNode1.textValue(), equalTo("v1"));

timestamp解析, string –> timestamp

stackoverflow

class UnixTimestampDeserializer extends JsonDeserializer<DateTime> 

class TimestampThing {
    @JsonDeserialize(using = UnixTimestampDeserializer.class)
    DateTime timestamp

    @JsonCreator
    public TimestampThing(@JsonProperty('timestamp') DateTime timestamp) {
        this.timestamp = timestamp
    }
}