Reputation: 517
This is My String
{Line:1,Direction:incoming,LocalUsername:xxx,AuthUsername:31223,PeerUsername:04232000113,Name:04232000113,Server:23424,Connectime:2189msec,Duration:0msec,DiscBy:Remote,Reason:cancelNormalcallclearing}
i want to convert it to json string
{"Line":"1","Direction":"incoming","LocalUsername":"xxx","AuthUsername":"31223","PeerUsername":"04232000113","Name":"04232000113","Server":"23424","Connectime":"2189msec","Duration":"0msec","DiscBy":"Remote"}
Upvotes: 0
Views: 2011
Reputation: 21
Try using Gson library
Gson g = new Gson();
Player p = g.fromJson(jsonString, Player.class)
You can also convert a Java object to JSON by using toJson() method as shown below
String str = g.toJson(p);
If you don't have a POJO representing the data, it can be done generally using JsonElement
.
Demo
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);
Output
{"Line":1,"Direction":"incoming","LocalUsername":"xxx","AuthUsername":31223,"PeerUsername":"04232000113","Name":"04232000113","Server":23424,"Connectime":"2189msec","Duration":"0msec","DiscBy":"Remote","Reason":"cancelNormalcallclearing"}
Upvotes: 2
Reputation: 159215
Since it isn't nested, simply add "
around :
and ,
, and after {
and before }
:
s = s.replaceAll("(?<=[{:,])|(?=[:,}])", "\"");
See demo on regex101.com.
Upvotes: 2