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的详细使用记录相关推荐

  1. 用jackson封装的JSON工具类

    package hjp.smart4j.framework.util;import com.fasterxml.jackson.databind.ObjectMapper; import org.sl ...

  2. Code片段 : .properties属性文件操作工具类 JSON工具类

    摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢! "贵专" - 泥瓦匠 一.java.util.Properties API ...

  3. 常用JSON工具类JsonUtil封装

    前言 项目中经常会有String转Object以及Object转Json字符串的需求,故封装一个常用Json工具类 Maven依赖 <dependency><groupId>o ...

  4. java实用工具类——java处理对象转json工具类

    一.引言 json字符串现在是项目中很常用的了,尤其是在写接口返回数据一般都是json格式的.小编最近在看项目中,发现有多处地方用到了java对象转json,但是引用的jar包都是不统一的. 常见的有 ...

  5. SpringBoot的JSON工具类(java),用于前后端分离

    简介 JSON(JavaScript Object Notation, JS对象简谱)是一种轻量级的数据交换格式.它基于 ECMAScript(European Computer Manufactur ...

  6. Json工具类 - JsonUtils.java

    Json工具类,提供Json与对象之间的转换. 源码如下:(点击下载 - JsonUtils.java . gson-2.2.4.jar ) 1 import java.lang.reflect.Ty ...

  7. 简易的组装Json工具类

    简易的组装Json工具类 // 设置业务参数 aliPayRequest.setBizContent("{" +" \"out_trade_no\": ...

  8. Json工具类的使用

    学习目标: 掌握两种Json工具类的使用 学习内容: 1.Json对象的创建和设定 2.Json对象转字符串 3.Json字符串转实体类 4.字符串转Json对象 5.Json字符串转Json数组 6 ...

  9. JSON基础及Java的JSON工具类

    一.JSON基础 定义:JSON(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式.它基于 ECMAScript (欧洲计算机协会制定的js规范)的 ...

最新文章

  1. Java实现无向图的邻接列表表示,深度遍历及广度遍历
  2. 我的R之路:参数假设检验
  3. keepalived热备 keepalived+LVS Haproxy
  4. VM虚拟机不能上网的问题解决
  5. mysql数据库安全机制研究意义_MySQL数据库的安全机制
  6. python用海伦公式求面积_Python:平面直角坐标系下用三点求所构三角形面积
  7. Python官方文档学习心得(第四篇)
  8. 正则表达式的三种模式【贪婪、勉强、侵占】的分析
  9. 这个 bug 可劫持同一 WiFi 网络上所有的安卓版火狐移动浏览器
  10. 【Assembly】Mixed mode dll unable to load in .net 4.0
  11. 读书:冯友兰的《中国哲学简史》
  12. mongodb 复制(副本集)
  13. 沙绿色background-color:#e5eecc; border:solid 1px #c3c3c3;
  14. 趣味计算机课堂示范课,枯燥的理工学科,秒变趣味课堂
  15. ISG2014 Writeups
  16. 审计机构不用计算机审计,计算机审计存在哪些风险
  17. java 控制台聊天昵称_简单的java控制台聊天室实现
  18. webpack.base.conf.js文件
  19. Python 数字筛选
  20. Python函数式编程:map/reduce

热门文章

  1. 事务里面捕获异常_spring 事务回滚
  2. java atm模拟系统_Java RPC模式开发一个银行atm模拟系统
  3. java mysql 操作类_Java 数据库简单操作类
  4. linux一切对象皆文件,为什么说Linux下“一切皆文件”?
  5. 下列选项中 采用边界值平滑_使用Illustrator中的混合工具创建很有个性的蛋宝宝...
  6. SVM支持向量机详解
  7. NLP神器—Gensim
  8. 多游课堂C++ 百万并发网络通信引擎架构与实现学习笔记
  9. 预训练模型真的越大越好吗?听听他们怎么说
  10. AAAI 2021 | 用于图拓扑演化的深度图谱进化网络