Quoted string output
I am getting put line as shown below
{key: IsReprint, value: COPY}; {key: IsCancelled, value: CANCELED}
I want to convert above string like below in my output ... I want to add quotes to string (key, value pairs).
{"key": "IsReprint", "value":"COPY"};{"key": "IsCancelled", "value":"CANCELLED"}
Please help .. 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 have above code has problem if input line is below
{key: BDTV, value: Africa Ltd | Reg. No .: 433323240833-C23441, GffBLAB | VAT number: 4746660239035
Level 6}
source to share
You can use a regular expression to accomplish the same, but more succinctly:
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 may need to tweak the regex or output string to suit your exact requirements, but that should give you an idea of how to start ...
source to share
How do I escape a string in Java?
For example:
String s = "{\" key \ ": \" IsReprint \ "; // will be printed as {" key ":" IsReprint "
source to share
This gives the exact result you want!
public static void main(String s[]){
String test = "{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}";
StringBuilder sb= new StringBuilder();
String[] keyValOld = test.split(";");
for(int j=0; j<keyValOld.length; j++){
String keyVal = keyValOld[j].substring(1,keyValOld[j].length()-1);
String[] parts = keyVal.split("(:)|(,)",4);
sb.append("{");
for (int i = 0; i < parts.length; i += 2) {
sb.append("\""+parts[i].trim()+"\": \""+parts[i + 1].trim()+"\"");
if(i+2<parts.length) sb.append(", ");
}
sb.append("};");
}
System.out.println(sb.toString());
}
source to share
Here is a solution using regexp to split your input into key / value pairs and then aggregate the result in the format you want:
// Split key value pairs
final String regexp = "\\{(.*?)\\}";
final Pattern p = Pattern.compile(regexp);
final Matcher m = p.matcher(input);
final List<String[]> keyValuePairs = new ArrayList<>();
while (m.find())
{
final String[] keyValue = input.substring(m.start() + 1, m.end() - 1) // "key: IsReprint, value:COPY"
.substring(5) // "IsReprint, value:COPY"
.split(", value:"); // ["IsReprint", "COPY"]
keyValuePairs.add(keyValue);
}
// Aggregate
final List<String> newKeyValuePairs = keyValuePairs.stream().map(keyValue ->
{
return "{\"key\": \"" + keyValue[0] + "\", \"value\":\"" + keyValue[1] + "\"}";
}).collect(Collectors.toList());
System.out.println(StringUtils.join(newKeyValuePairs.toArray(), ";"));
Result for the next input line
final String input = "{key: IsReprint, value:COPY};{key: IsCancelled, value:CANCELLED};{key: BDTV, value:Africa Ltd | Reg No: 433323240833-C23441,GffBLAB | VAT No: 4746660239035<br />Level 6}";
there is {"key": "IsReprint", "value":"COPY"};{"key": "IsCancelled", "value":"CANCELLED"};{"key": "BDTV", "value":"Africa Ltd | Reg No: 433323240833-C23441,GffBLAB | VAT No: 4746660239035<br />Level 6"}
source to share
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NewClass {
public static void main(String[] args) {
String input="{key: IsReprint, value:COPY};{key: IsCancelled, value:CANCELLED};{key: BDTV,value:Africa Ltd | Reg No: 433323240833-C23441,GffBLAB | VAT No: 4746660239035 Level 6}";
Matcher m1 = Pattern.compile("key:" + "(.*?)" + ",\\s*value:").matcher(input);
Matcher m2 = Pattern.compile("value:" + "(.*?)" + "}").matcher(input);
StringBuilder sb = new StringBuilder();
while(m1.find() && m2.find()){
sb.append("{\"key\": ")
.append("\"")
.append(m1.group(1).trim())
.append("\", \"value\":")
.append("\"")
.append(m2.group(1).trim())
.append("\"};");
}
String output = sb.deleteCharAt(sb.length()-1).toString();
System.out.println(output);
}
}
source to share