json工具类ObjectMapper的详细使用记录
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 configureFile newState = new File("my-stuff.json");mapper.writeValue(newState, value); // writes JSON serialization of MyValue instance// or, readMyValue 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; @Testpublic 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串寫入到文件中:
結果:
使用toJsonListObject得到json轉化而來的對象:
輸出
[蘋果, 梨子, 車, 人]
一些相關注解:
@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)。
總結
以上是生活随笔為你收集整理的json工具类ObjectMapper的详细使用记录的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java的格式化时间工具类
- 下一篇: redis+springboot实现购物