Java实现生成JSON字符串的三种方式分享
作者:张二三 时间:2022-05-20 15:21:31
我的安卓开发经历始于一个原生安卓项目开发。后来由于公司有个项目与几家医疗设备公司合作,需要我写安卓端的桥接代码给 react native 端的同事调用。刚开始,对于一些流程的也不懂,直接调用 toString 就给 RN 了,给 RN 端的数据就是比如 {code=NOT_INITIALIZED, message=Please initialize library}
,导致 RN 端的同事需要自己写解析代码获取 key 和 value,联调麻烦。后来去研究如何转成 json 字符串给 RN 端,联调就顺畅多了
下面以错误处理返回的 code 和 message 为例,演示如何拼接 JSON 字符串
// 演示数据
String code = "NOT_INITIALIZED";
String message = "Please initialize library";
手动拼接(不推荐)
我们看 json 的结构,key 和 string 类型的 value 的都是需要前后加双引号的,java 没有 js 的 ''
或 ``,那怎么插入双引号呢,答案是使用反斜杠加字符串
对于 char
和 String
变量,拼接比较麻烦
char c1 = 'c';
String s1 = "s1";
System.out.println("{" + "\"c1\":" + "\"" + c1 + "\"" + "}");
System.out.println("{" + "\"s1\":" + "\"" + s1 + "\"" + "}");
其他类型的变量,拼接就比较简单了
boolean b1 = true;
float f1 = 34f;
double d1 = 33.2d;
System.out.println("{" + "\"b1\":" + b1 + "}");
System.out.println("{" + "\"f1\":" + f1 + "}");
System.out.println("{" + "\"d1\":" + d1 + "}");
因此,对于上面提到的数据,拼接的话就是下面这样
String jsonStr = "{" + "\"code\":" + "\"" + code + "\"" + "," + "\"message\":" + "\"" + message + "\"" + "}";
为什么不推荐这种方式呢?数据量少还好,多了的话可能会遇到逗号忘写,字符串忘加前后置反斜杠双引号的情况,调试费时间
使用 Gson 等 JSON 库
1.定义一个数据类
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;
}
}
2.使用 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();
为什么推荐这种方式呢?两个原因,第一,使用起来比前两种方式都方便;第二,假如你是原生开发安卓的话,那你大概率会引入一个 JSON 库来实现前后端配合,创建一个数据类搭配 GSON 可比 jsonObject.getString
使用起来方便多了,但像我司主要是 RN 项目,为了一个小功能而引入一个库实在是不划算,这时就是 JSONObject 的用武之地了
来源:https://juejin.cn/post/7229923818348199973
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
mybatis-plus配置控制台打印完整带参数SQL语句的实现
ThreadLocal工作原理及用法案例
java通过方向键控制小球移动的小游戏
jvm调优的几种场景(小结)
![](https://img.aspxhome.com/file/2023/3/60323_0s.png)
关于EntityWrapper的in用法
![](https://img.aspxhome.com/file/2023/3/60353_0s.png)
Java遗传算法之冲出迷宫
Java中instanceof关键字实例讲解
![](https://img.aspxhome.com/file/2023/5/63305_0s.png)
springboot v2.0.3版本多数据源配置方法
![](https://img.aspxhome.com/file/2023/5/57825_0s.png)
Java线程编程中isAlive()和join()的使用详解
浅谈c++性能测试工具之计算时间复杂度
![](https://img.aspxhome.com/file/2023/4/79524_0s.jpg)
java去除字符串中的空格、回车、换行符、制表符的小例子
java分页工具类的使用方法
IDEA安装后找不到.vmoptions文件的问题及解决
![](https://img.aspxhome.com/file/2023/5/58475_0s.png)
SpringBoot项目@Async方法问题解决方案
![](https://img.aspxhome.com/file/2023/2/58872_0s.png)
Java使用IO流实现音频的剪切和拼接
![](https://img.aspxhome.com/file/2023/9/58189_0s.jpg)
Java中synchronized的几种使用方法
![](https://img.aspxhome.com/file/2023/8/62228_0s.webp)
Android学习笔记-保存数据到SQL数据库中(Saving Data in SQL Databases)
![](https://img.aspxhome.com/file/2023/2/83532_0s.png)
idea如何配置javafxsdk详细教程
![](https://img.aspxhome.com/file/2023/3/59603_0s.jpg)