Murali
Murali

Reputation: 53

String output with quotes

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}

Upvotes: 3

Views: 222

Answers (6)

Eritrean
Eritrean

Reputation: 16498

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

Upvotes: 0

R Dhaval
R Dhaval

Reputation: 546

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());
}

Upvotes: 0

Emmanuel Guiton
Emmanuel Guiton

Reputation: 1445

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

Upvotes: 0

6006604
6006604

Reputation: 7789

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

Upvotes: 3

Martin
Martin

Reputation: 41

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

Upvotes: 0

Yuri H
Yuri H

Reputation: 680

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"

Upvotes: 0

Related Questions