0

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"}

2 Answers 2

2

Since it isn't nested, simply add " around : and ,, and after { and before }:

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

See demo on regex101.com.

Sign up to request clarification or add additional context in comments.

Comments

2

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"}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.