I get in put string as below
{key: IsReprint, value:COPY};{key: IsCancelled, value:CANCELLED}
I want to convert above string as below in my output...,want to add quotes to the string (key , value pairs).
{"key": "IsReprint", "value":"COPY"};{"key": "IsCancelled", "value":"CANCELLED"}
Please assist..thanks in advance..
String input="{key: IsReprint, value:COPY};{key: IsCancelled,value:CANCELLED}";
if(input.contains("key:") && input.contains("value:") ){
input=input.replaceAll("key", "\"key\"");
input=input.replaceAll("value", "\"value\"");
input=input.replaceAll(":", ":\"");
input=input.replaceAll("}", "\"}");
input=input.replaceAll(",", "\",");
//System.out.println("OUTPUT----> "+input);
}
I above code has problem if input string as below
{key: BDTV, value:Africa Ltd | Reg No: 433323240833-C23441,GffBLAB | VAT No: 4746660239035
Level 6}
You could use regex to accomplish the same, but more concisely:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JsonScanner {
private final static String JSON_REGEX = "\\{key: (.*?), value:(.*?)(\\};|\\}$)";
/**
* Splits the JSON string into key/value tokens.
*
* @param json the JSON string to format
* @return the formatted JSON string
*/
private String findMatched(String json) {
Pattern p = Pattern.compile(JSON_REGEX);
Matcher m = p.matcher(json);
StringBuilder result = new StringBuilder();
while (m.find()) {
result.append("\"key\"=\"" + m.group(1) + "\", ");
result.append("\"value\"=\"" + m.group(2) + "\" ; ");
System.out.println("m.group(1)=" + m.group(1) + " ");
System.out.println("m.group(2)=" + m.group(2) + " ");
System.out.println("m.group(3)=" + m.group(3) + "\n");
}
return result.toString();
}
public static void main(String... args) {
JsonScanner jsonScanner = new JsonScanner();
String result = jsonScanner.findMatched("{key: TVREG, value:WestAfrica Ltd | VAT No: 1009034324829/{834324}<br/>Plot No.56634773,Road};{key: REGISTRATION, value:SouthAfricaLtd | VAT No: 1009034324829/{834324}<br />Plot No. 56634773, Road}");
System.out.println(result);
}
}
You might have to tweak the regex or output string to meet your exact requirements, but this should give you an idea of how to get started...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With