JAVA如何生成JSON字符串呢?

戚薇 fastjson 发布时间:2023-05-12 21:52:49 阅读数:4347 1
下文笔者讲述使用java代码生成json字符串的方法分享,如下所示
在前端和后端
  各系统之间的交互,我们通常会采用json字符串进行传输
那么java代码如何生成json字符串呢?
下文笔者将讲述以下三种方法,如下所示

生成json字符串的方式

方式1:
  采用字符串方式拼接

方式2:
  使用Gson中库 toJSON方法
   将实体类转换为JSON字符串

方式3:
  使用new JSONObject(实体类).toString()
例:生成JSON字符串
 
// 演示数据
String code = "1";
String message = "success"; 
String jsonStr = "{" + "\"code\":" + "\"" + code + "\"" + "," + "\"message\":" + "\"" + message + "\"" + "}";

使用Gson等JSON库

定义一个实体类
class ErrorInfo {
    private String code;
    private String message;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}
使用 Gson 的 toJson 方法
import com.google.gson.Gson;

ErrorInfo errorInfo = new ErrorInfo();
errorInfo.setCode(code);
errorInfo.setMessage(message);
Gson gson = new Gson();
String jsonStr = gson.toJson(errorInfo);

使用 JSONObject(推荐)

import org.json.JSONObject;

JSONObject jsonObject = new JSONObject();
String jsonStr = "";
try {
    jsonObject.put("code", code);
    jsonObject.put("message", message);
    jsonStr = jsonObject.toString();
} catch (JSONException e) {
    throw new RuntimeException(e);
}

//为避免 try catch
//倾向于结合HashMap使用

HashMap<String, String> map = new HashMap<>();
map.put("code", code);
map.put("message", message);
String jsonStr = new JSONObject(map).toString();
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/fastjson/2023/6423.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者