java restful返回json_restful返回 json数据的JavaBean设计

本文介绍了一个名为`ResultEntity`的Java类,用于构建RESTful API的JSON响应。该类基于FastJSON库,提供了一种方便的方式来设置响应的`code`、`message`和`data`字段,并允许添加嵌套数据。通过`put`和`putNest`方法,可以动态添加键值对到JSON对象中,确保了响应结构的一致性。
摘要由CSDN通过智能技术生成

import com.alibaba.fastjson.JSONObject;

import java.io.Serializable;

import java.util.Map;

public class ResultEntity implements Serializable {

JSONObject jsonObject;

public JSONObject getJsonObject() {

return jsonObject;

}

public void setJsonObject(JSONObject jsonObject) {

this.jsonObject = jsonObject;

}

public ResultEntity() {

this.jsonObject = new JSONObject();

}

public ResultEntity(JSONObject object) {

this.jsonObject = object;

}

public ResultEntity(int code, String message) {

this();

this.jsonObject.put("code", code);

this.jsonObject.put("message", message);

}

public ResultEntity(int code, String message, String description) {

this();

this.jsonObject.put("code", code);

this.jsonObject.put("message", message);

if (description != null) {

this.jsonObject.put("description", description);

}

}

public ResultEntity put(String key, Object value) {

this.jsonObject.put(key, value);

return this;

}

public ResultEntity put(Map map) {

for (String key : map.keySet()) {

this.jsonObject.put(key, map.get(key));

}

return this;

}

public ResultEntity putNest(String key, Object value) {

if (!jsonObject.containsKey("data")) {

JSONObject dataObj = new JSONObject();

jsonObject.put("data", dataObj);

}

this.jsonObject.getJSONObject("data").put(key, value);

return this;

}

public ResultEntity putNest(Map map) {

if (!jsonObject.containsKey("data")) {

JSONObject dataObj = new JSONObject();

jsonObject.put("data", dataObj);

}

for (String key : map.keySet()) {

this.jsonObject.getJSONObject("data").put(key, map.get(key));

}

return this;

}

public String toJsonString() {

return this.jsonObject.toString();

}

public Map totMap() {

return this.jsonObject;

}

}

调用示例:

方式一:

return new ResultEntity(0,"保存成功").putNest("name","张三").putNest("sex","男");

方式二:

Map map = new HashMap();

map.putNest("name","张三");

map.putNest("sex","男");

return new ResultEntity(0,"保存成功").putNest(map);

结果:

{

"code":0,

"message":"保存成功",

"data":{

"name":"张三",

"sex":"男"

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值