ObjectMapper中的writeVaule和writeValueAsString方法之间的关系

您所在的位置:网站首页 jackson是什么中文意思 ObjectMapper中的writeVaule和writeValueAsString方法之间的关系

ObjectMapper中的writeVaule和writeValueAsString方法之间的关系

#ObjectMapper中的writeVaule和writeValueAsString方法之间的关系| 来源: 网络整理| 查看: 265

ObjectMapper介绍

  ObjectMapper是Jackson库中主要用于读取和写入Json数据的类,能够很方便地将Java对象转为Json格式的数据,用于后端Servlet向AJAX传递Json数据,动态地将数据展示在页面上。为了能够使用这个类,需要先下载Jackson库。

下载地址:https://mvnrepository.com/artifact/com.fasterxml.jackson.core 参考方式:https://www.cnblogs.com/libin6505/p/10132674.html

1、writeValue()

列举两种常用的writeValue方法(假设student为Java对象)

/* 方法定义 */ public void writeValue(Writer w, Object value); /* 例子如下 */ ObjectMapper mapper = new ObjectMapper(); PrintWriter printwriter = res.getWriter(); mapper.writeValue(printwriter, student); /* 方法定义 */ public void writeValue(OutputStream out, Object value); /* 例子如下 */ ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(res.getOutputStream(), student);

注意: 1、res为HttpServletResponse的实例对象。     2、该方法没有返回值,方法执行后student转为Json格式的数据。     3、前者的定义返回的是字符流,后者的定义返回的是字节流。

2、writeValueAsString()

该方法只有唯一定义(假设student为Java对象)

/* 方法定义 */ public String writeValueAsString(Object value); /* 例子如下 */ ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(student); res.getWriter().write(json);

注意: 1、res为HttpServletResponse的实例对象     2、该方法有返回值,返回的是一个String对象。    3、该方法和writeValue(Writer w, Object value)是等价的。

3、二者之间的关系

  两种不同的方法都是把Java对象(student)转为Json格式的数据响应到页面中,writeValue没有返回值,但它实际上也是把student转为String类型的数据,并且是以Json的格式进行存储,数据返回到前端中可以直接进行解析。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3