3

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}

Murali
  • 53
  • 7

6 Answers6

3

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...

6006604
  • 7,577
  • 1
  • 22
  • 30
  • Thanks 6006604,but I used below .It didnt give exact result.Can you try below input string .. String result = jsonScanner.findMatched("{key: TVREG, value:WestAfrica Ltd | VAT No: 1009034324829/{834324}
    Plot No.56634773,Road};{key: REGISTRATION, value:SouthAfricaLtd | VAT No: 1009034324829/{834324}
    Plot No. 56634773, Road}");
    – Murali May 29 '17 at 13:06
  • I tweaked the regex and added some debugging logs to show what the regex is capturing. there might be a more elegant way to write the regex, but this seems to work... – 6006604 May 29 '17 at 13:50
  • Wow...This worked.Thanks a lot.Let me test for different scenarios. – Murali May 29 '17 at 14:49
0

You have to escape characters

How do I escape a string in Java?

For example:
String s = "{\"key\": \"IsReprint\""; // will be print as {"key": "IsReprint"

Yuri H
  • 680
  • 5
  • 12
  • @Bala Murali Can you close the question? [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers) – Yuri H May 29 '17 at 10:54
  • I think you should cast all elements of the string to the unified standard. Otherwise, you'll have to deal with different cases and create code for their replacement. i.e. In case ":" and ": " you have to foresee both situations in your code. – Yuri H May 29 '17 at 11:28
  • Well, I can't come up with a simple and grateful solution, so I can only advice such a solution: input=input.replaceAll(": ", ":").replaceAll(":", ": \""); – Yuri H May 29 '17 at 12:37
0

The double quote character has to be escaped with a backslash in a Java string literal. Other characters that need special treatment include:

Carriage return and newline: "\r" and "\n" Backslash: "\" Single quote: "\'" Horizontal tab and form feed: "\t" and "\f".

Martin
  • 41
  • 1
  • 8
0

This gives the exact result as 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());
}
R Dhaval
  • 536
  • 1
  • 9
  • 21
  • It will remove _all the spaces_ in the string. I guess it won't be a desirable result. – Yuri H May 29 '17 at 12:00
  • Moreover, it adds additional symbols: "{" "}" – Yuri H May 29 '17 at 12:01
  • Thanks ..but if my string as below then it is problem ..{key: TVREG, value:WestAfrica Ltd | VAT No: 1009034324829/{834324}
    Plot No. 56634773, Road};{key: REGISTRATION, value:SouthAfricaLtd | VAT No: 1009034324829/{834324}
    Plot No. 56634773, Road}
    – Murali May 29 '17 at 12:03
  • Thanks Yuri... you are right...if data has addintional {,} ,: values in Value then its problem – Murali May 29 '17 at 12:04
  • my bad guys.. forgot to add elseif instead of if.. silly copy paste :) now it is not addng additional chars – R Dhaval May 29 '17 at 12:08
  • @RDR,if my input string is as ".{key: TVREG, value:WestAfrica Ltd | VAT No: 1009034324829/{834324}
    Plot No. 56634773, Road};{key: REGISTRATION, value:SouthAfricaLtd | VAT No: 1009034324829/{834324}
    Plot No. 56634773, Road} " ..THEN I AM GETTING PROBLEM...CAN YOU PLS TRY THIS INPUT STRING
    – Murali May 29 '17 at 12:11
  • {"key": "TVREG", "value": "WestAfricaLtd|VATNo": "1009034324829/{"834324"}
    PlotNo.56634773", "Road"};{"key": "REGISTRATION", "value": "SouthAfricaLtd|VATNo": "1009034324829/{"834324"}
    PlotNo.56634773", "Road"} I am getting this.. tell me what should be the O/P
    – R Dhaval May 29 '17 at 12:12
  • I WANT FINAL OUT PUT STRING AS BELOW :::: ".{"key": "TVREG", "value":"WestAfrica Ltd | VAT No: 1009034324829/{834324}
    Plot No. 56634773, Road"};{"key": "REGISTRATION", "value":"SouthAfricaLtd | VAT No: 1009034324829/{834324}
    Plot No. 56634773, Road"}
    – Murali May 29 '17 at 12:12
  • @RDR ,,If see my input string its having KEY VALUE PAIRS...i want the key and values should be in the double quotes..That is my requirement. – Murali May 29 '17 at 12:18
  • updated the answer. It is still half of the solution. I will update once I get time – R Dhaval May 29 '17 at 12:55
0

Here is a solution using a regexp to split your input into key / value pairs and then aggregating the result using the format you wish :

// 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(), ";"));

The result for the folowing input string

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

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

Emmanuel Guiton
  • 1,315
  • 13
  • 24
  • Thanks Emmanuel, but I am getting compilation errors at // Aggregate block.. // Aggregate final List newKeyValuePairs = keyValuePairs.stream().map(keyValue -> { return "{\"key\": \"" + keyValue[0] + "\", \"value\":\"" + keyValue[1] + "\"}"; }).collect(Collectors.toList());Can you kindly check this statement – Murali May 29 '17 at 14:31
  • Well, difficult to say without knowing what is the error. Could you give us the error message ? The code compiles just fine on my computer. What version of Java do you use ? You are pointing at a line that uses Java 8 tools (Stream). – Emmanuel Guiton May 29 '17 at 15:03
  • If you are not using Java 8, you can just iterate with a for loop to replace the Stream : final List newKeyValuePairs = new ArrayList<>(); for (final String[] keyValue : keyValuePairs) { newKeyValuePairs.add("{\"key\": \"" + keyValue[0] + "\", \"value\":\"" + keyValue[1] + "\"}"); } – Emmanuel Guiton May 29 '17 at 15:08
0
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);
    }    
}
Eritrean
  • 15,851
  • 3
  • 22
  • 28