2021-10-13

**

JSON转换(二)

**


前言

众所周知,在非RESTful方式下去创建接口是不会得到JSON格式的数据的,那么为了得到JSON格式的数据,我们需要利用JSON转换得到JSON数据。


一、JSON转换是什么?

在了解JSON转换是什么之前,我们需要了解什么是JSON数据格式:
JSON基本结构设计

{
  "success": 布尔, //响应是否成功
  "code": 数字, //响应码
  "message": 字符串, //返回消息
  "data": HashMap //返回数据,放在键值对中,如果是空,{}
}

这种JSON数据格式可以是列表,也可以是分页。
列表形式:列表的标志就是items。

{
  "success": true,
  "code": 20000,
  "message": "成功",
  "data": {
    "items": [
      {
        "id": "1",
        "name": "11",
        "intro": "111"
      }
    ]
  }
}

分页形式:分页会有一个total项,还有一个rows项。

{
  "success": true,
  "code": 20000,
  "message": "成功",
  "data": {
    "total": 1111,
    "rows": [
      {
        "id": "1",
        "name": "11",
        "intro": "111"
      }
    ]
  }
}

我们的数据一开始可能只是列表的形式,但是我们要转换成JSON的格式,这里就需要JSON转换,今天我们将分析使用Gson去进行JSON转换。

二、Gson简要使用

Gson和其他现有Java json类库最大的不同时Gson需要序列化得实体类不需要使用annotation来标识需要序列化得字段,同时Gson又可以通过使用annotation来灵活配置需要序列化的字段。Gson的反序列化,Gson提供了fromJson()方法来实现从Json相关对象到java实体的方法。那么Gson的序列化,就是将java实体转换成Json对象。还有我们刚刚分析了列表方式,如何转换成列表了,我们可以使用TypeToken,它是gson提供的数据类型转换器,可以支持各种数据集合类型转换。我们来看一下下面的两个例子:

Person person = gson.fromJson(str, Person.class);
//将Person  Json对象转化为person 实体对象
List<Person> ps = gson.fromJson(str, new TypeToken<List<Person>>(){}.getType());
for(int i = 0; i < ps.size() ; i++)
{
     Person p = ps.get(i);
     System.out.println(p.toString());
}
//转化成列表类型

案例

1.建立实体类

import java.util.Date;
 
public class News {
 
	private int nId; // 新闻ID
	private String title; // 新闻标题
	private String content; // 新闻内容
	private String date; // 新闻发布日期
	private String url; //新闻地址
	private Date nDate; // 新闻日期,Date类型
 
	public News(int nId, String title, String content, String date, String url) {
		this.nId = nId;
		this.title = title;
		this.content = content;
		this.date = date;
		this.url = url;
	}
 
	public News() {
	}
 
	public News(int nId, String title, String content, Date nDate, String url) {
		this.nId = nId;
		this.title = title;
		this.content = content;
		this.nDate = nDate;
		this.url = url;
	}
 
	
	
	public String getUrl() {
		return url;
	}
 
	public void setUrl(String url) {
		this.url = url;
	}
 
	public Date getnDate() {
		return nDate;
	}
 
	public void setnDate(Date nDate) {
		this.nDate = nDate;
	}
 
	public int getnId() {
		return nId;
	}
 
	public void setnId(int nId) {
		this.nId = nId;
	}
 
	public String getTitle() {
		return title;
	}
 
	public void setTitle(String title) {
		this.title = title;
	}
 
	public String getContent() {
		return content;
	}
 
	public void setContent(String content) {
		this.content = content;
	}
 
	public String getDate() {
		return date;
	}
 
	public void setDate(String date) {
		this.date = date;
	}
 
}

2.建立分页实体类,主要有分页操作

import java.util.List;
 
public class NewTotal {
	private int total; //新闻数量
	private List<News> rows; //新闻列表
	
	
	public NewTotal() {
	}
	public NewTotal(int total, List<News> rows) {
		this.total = total;
		this.rows = rows;
	}
	public int getTotal() {
		return total;
	}
	public void setTotal(int total) {
		this.total = total;
	}
	public List<News> getRows() {
		return rows;
	}
	public void setRows(List<News> rows) {
		this.rows = rows;
	}
	
	
}

3.测试

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.google.gson.Gson;
import com.test.model.NewTotal;
import com.test.model.News;
 
public class JsonServlet extends HttpServlet {
 
	private static final long serialVersionUID = 1L;
 
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 创建多个新闻类,模拟从数据库获取数据,可将此处改为用JDBC从数据库读取数据,结构:id,标题,图片,发布时间,网址
		News new1 = new News(110, "微视频|为了人民当家作主", "为了人民当家作主", "2016-5-16 10:22:20",
				"https://news.sina.com.cn/gov/xlxw/2021-10-13/doc-iktzqtyu1133163.shtml");
		News new2 = new News(111, "Apple库克第八次访华", "近日库克第八次访华,与滴滴高层会谈", "2016-5-16 10:22:20",				"http://mobile.163.com/16/0523/09/BNO7SG2B001168BQ.html");
		
 
		String page = req.getParameter("page");
		// 将数据添加到数组
		List<News> newslist = new ArrayList<News>();
		if (page == null || page.equals("0")) {
			newslist.add(new1);
		}
		else {
			newslist.add(new2);
		}
 
		// 将数据封装到新闻总计类
		NewTotal nt = new NewTotal(newslist.size(), newslist);
 
		// 调用GSON jar工具包封装好的toJson方法,可直接生成JSON字符串
		Gson gson = new Gson();
		String json = gson.toJson(nt);
 
		// 输出到界面
		System.out.println(json);
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("gb2312");
		PrintWriter out = new PrintWriter(resp.getOutputStream());
		out.print(json);
		out.flush();
		// 更多Json转换使用请看JsonTest类
	}
 
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doGet(req, resp);
	}
 
}

这里就回答了上面的问题,如何将java实体对象转换json对象,我们使用可toJSON()方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值