1。用于json与其他对象之间转化的工具类:

public class JsonUtil {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);

static {
MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}

public static <T> String toJsonStr(T o) {
try {
return MAPPER.writeValueAsString(o);//json转化为string
} catch (JsonProcessingException e) {
logger.error(e.getMessage(), e);
}
return null;
}

public static <T> T toJsonObject(String json, Class<T> valueType) {
try {
return MAPPER.<T>readValue(json, valueType);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return null;
}


public static <T> List<T> toJsonListObject(String json, Class<T> valueType) {
try {
JavaType getCollectionType = MAPPER.getTypeFactory().constructParametricType(List.class, valueType);
List<T> list = MAPPER.readValue(json, getCollectionType);
return list;
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return null;
}

public static <T> T toJsonObject(InputStream stream, Class<T> valueType) {
try {
T object = MAPPER.<T>readValue(stream, valueType);
return object;
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return null;
}
}

将文件与对象关联的解析类:

public class JSON
{
public static final String DEFAULT_FAIL = "\"Parse failed\"";
private static final ObjectMapper objectMapper = new ObjectMapper();
private static final ObjectWriter objectWriter = objectMapper.writerWithDefaultPrettyPrinter();
//.writerWithDefaultPrettyPrinter();用于输出时的格式化
public static void marshal(File file, Object value) throws Exception
{
try
{
objectWriter.writeValue(file, value);
}
catch (JsonGenerationException e)
{
throw new Exception(e);
}
catch (JsonMappingException e)
{
throw new Exception(e);
}
catch (IOException e)
{
throw new Exception(e);
}
}

public static void marshal(OutputStream os, Object value) throws Exception
{
try
{
objectWriter.writeValue(os, value);
}
catch (JsonGenerationException e)
{
throw new Exception(e);
}
catch (JsonMappingException e)
{
throw new Exception(e);
}
catch (IOException e)
{
throw new Exception(e);
}
}

public static String marshal(Object value) throws Exception
{
try
{
return objectWriter.writeValueAsString(value);
}
catch (JsonGenerationException e)
{
throw new Exception(e);
}
catch (JsonMappingException e)
{
throw new Exception(e);
}
catch (IOException e)
{
throw new Exception(e);
}
}

public static byte[] marshalBytes(Object value) throws Exception
{
try
{
return objectWriter.writeValueAsBytes(value);
}
catch (JsonGenerationException e)
{
throw new Exception(e);
}
catch (JsonMappingException e)
{
throw new Exception(e);
}
catch (IOException e)
{
throw new Exception(e);
}
}

public static <T> T unmarshal(File file, Class<T> valueType) throws Exception
{
try
{
return objectMapper.readValue(file, valueType);
}
catch (JsonParseException e)
{
throw new Exception(e);
}
catch (JsonMappingException e)
{
throw new Exception(e);
}
catch (IOException e)
{
throw new Exception(e);
}
}

public static <T> T unmarshal(InputStream is, Class<T> valueType) throws Exception
{
try
{
return objectMapper.readValue(is, valueType);
}
catch (JsonParseException e)
{
throw new Exception(e);
}
catch (JsonMappingException e)
{
throw new Exception(e);
}
catch (IOException e)
{
throw new Exception(e);
}
}

public static <T> T unmarshal(String str, Class<T> valueType) throws Exception
{
try
{
return objectMapper.readValue(str, valueType);
}
catch (JsonParseException e)
{
throw new Exception(e);
}
catch (JsonMappingException e)
{
throw new Exception(e);
}
catch (IOException e)
{
throw new Exception(e);
}
}

public static <T> T unmarshal(byte[] bytes, Class<T> valueType) throws Exception
{
try
{
if (bytes == null)
{
bytes = new byte[0];
}
return objectMapper.readValue(bytes, 0, bytes.length, valueType);
}
catch (JsonParseException e)
{
throw new Exception(e);
}
catch (JsonMappingException e)
{
throw new Exception(e);
}
catch (IOException e)
{
throw new Exception(e);
}
}
}

ObjectMapper 的一个使用例子:

final ObjectMapper mapper = new ObjectMapper(); // can use static singleton, inject: just make sure to reuse!
MyValue value = new MyValue();
// ... and configure
File newState = new File("my-stuff.json");
mapper.writeValue(newState, value); // writes JSON serialization of MyValue instance
// or, read
MyValue older = mapper.readValue(new File("my-older-stuff.json"), MyValue.class);

// Or if you prefer JSON Tree representation:
JsonNode root = mapper.readTree(newState);
// and find values by, for example, using a JsonPointer expression:
int age = root.at("/personal/age").getValueAsInt();

用ObjectMapper来输出一串json字符串:

import com.fasterxml.jackson.databind.ObjectMapper;
@Test
public void testJson() throws JsonProcessingException {
List<Word>blogs= wordMapper.selectAll();
String newjson = null;
ObjectMapper objectMapper = new ObjectMapper();
newjson= objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(blogs);
System.out.println(newjson);
newjson= JsonUtil.toJsonStr(blogs.getClass());
System.out.println(newjson.getBytes(StandardCharsets.UTF_8));

}

结果:

json工具类ObjectMapper的详细使用记录_List


把json串写入到文件中:

List<Word>blogs= wordMapper.selectAll();
String newjson = null;
ObjectMapper objectMapper = new ObjectMapper();
File newState = new File("my-stuff.json");
objectMapper.writeValue(newState,blogs);

结果:

json工具类ObjectMapper的详细使用记录_List_02


json工具类ObjectMapper的详细使用记录_List_03


使用toJsonListObject得到json转化而来的对象:

String newjson = "[{\"id\":1,\"english\":\"apple\",\"chinese\":\"苹果\",\"level\":1,\"frequency\":3,\"img\":\"http://localhost:8107/0.png\",\"usa\":\"an apple\"},\n" +
" {\"id\":2,\"english\":\"pear\",\"chinese\":\"梨子\",\"level\":2,\"frequency\":2,\"img\":\"http://localhost:8107/2.png\",\"usa\":\"eat pear\"},\n" +
" {\"id\":3,\"english\":\"car\",\"chinese\":\"车\",\"level\":1,\"frequency\":3,\"img\":null,\"usa\":\"cars(复数)buy car(买车)\"},{\"id\":4,\"english\":\"people\",\"chinese\":\"人\",\"level\":1,\"frequency\":3,\"img\":null,\"usa\":\"people(单复一样) we are people\"}]";




List<Word>blog2= JsonUtil.toJsonListObject(newjson,Word.class);
List<String>str = blog2.stream().map(e->{
String ch = e.getChinese();
return ch;
}).collect(Collectors.toList());
System.out.println(str);

输出
[苹果, 梨子, 车, 人]

一些相关注解:

@JsonInclude

//Include.Include.ALWAYS 默认
//Include.NON_DEFAULT 属性为默认值不序列化
//Include.NON_EMPTY 属性为 空(“”) 或者为 NULL 都不序列化
//Include.NON_NULL 属性为NULL 不序列化
@JsonProperty:用于指明属性的名称。
@JsonProperty(“create_date”)
private Date createDate;
此时将对象序列化以后得到的json串中上面的属性为create_date"
@JsonIgnore:用于忽略指定属性,当该注解出现在field、getter、setter或者构造方法中任意一个上时,都意味着忽略所有(即序列化和反序列化都被忽略);有一种情况,当getter上注解@JsonIgnore而setter上注解@JsonProperty,就会出现“只读”情况(read from input, but is not written output)。

@JsonIgnore

private String address;