如何在java中将字符串转换为json字符串和对象

wlp8pajw  于 2021-06-29  发布在  Java
关注(0)|答案(2)|浏览(438)

这是我的线

{Line:1,Direction:incoming,LocalUsername:xxx,AuthUsername:31223,PeerUsername:04232000113,Name:04232000113,Server:23424,Connectime:2189msec,Duration:0msec,DiscBy:Remote,Reason:cancelNormalcallclearing}

我想把它转换成json字符串

{"Line":"1","Direction":"incoming","LocalUsername":"xxx","AuthUsername":"31223","PeerUsername":"04232000113","Name":"04232000113","Server":"23424","Connectime":"2189msec","Duration":"0msec","DiscBy":"Remote"}
px9o7tmv

px9o7tmv1#

尝试使用gson库

Gson g = new Gson();
Player p = g.fromJson(jsonString, Player.class)

您还可以使用tojson()方法将java对象转换为json,如下所示

String str = g.toJson(p);

如果没有表示数据的pojo,通常可以使用 JsonElement .
演示

String input = "{Line:1,Direction:incoming,LocalUsername:xxx,AuthUsername:31223,PeerUsername:04232000113,Name:04232000113,Server:23424,Connectime:2189msec,Duration:0msec,DiscBy:Remote,Reason:cancelNormalcallclearing}";

Gson g = new Gson();
JsonElement root = g.fromJson(input, JsonElement.class);
String result = g.toJson(root);

System.out.println(result);

输出

{"Line":1,"Direction":"incoming","LocalUsername":"xxx","AuthUsername":31223,"PeerUsername":"04232000113","Name":"04232000113","Server":23424,"Connectime":"2189msec","Duration":"0msec","DiscBy":"Remote","Reason":"cancelNormalcallclearing"}
ar7v8xwq

ar7v8xwq2#

因为它不是嵌套的,所以只需添加 " 周围 : 以及 , ,之后 { 在那之前 } :

s = s.replaceAll("(?<=[{:,])|(?=[:,}])", "\"");

请参见regex101.com上的演示。

相关问题