日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發布時間:2024/9/30 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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串寫入到文件中:

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

結果:


使用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)。

@JsonIgnoreprivate String address;

總結

以上是生活随笔為你收集整理的json工具类ObjectMapper的详细使用记录的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。