Home > database >  Convert String into Key-Value Pair in Java
Convert String into Key-Value Pair in Java

Time:10-20

I know I there is a way to split using delimeter but the string I have is similar to JSON.

This is the string

[{type=Callback, output=[{name=prompt, value=InputCode}], input=[{name=IDT1, value=}]}, {type=TextOutputCallback, output=[{name=message, value={"current_type":"Code","info":{"some_key":"cf2fc86a","some_type":"Code","ph_no":"111111111"},"attempt":2}}]}]

Now I want to convert it in a way I can extract "attempt". So, I want to do something like this

String attempt = map.get("attempt");

The problem is that this isn't a valid JSON cause most of values aren't in double quotes. What would be the best way to extract that?

CodePudding user response:

The map from the given input using a regular expression to match and parse some values.

Assuming that valid keys are written as alphanumeric identifiers with optional underscore inside double quotes, and the values can be placed inside double quotes or as integer numbers, the following pattern may be implemented and used to build the map:

Pattern keyValue = Pattern.compile("(\"\\w \")\\s*:\\s*(\"[^\"] \"|\\d (.\\d )?)");
Map<String, String> map = keyValue.matcher(raw)
    .results()
    .collect(Collectors.toMap(
        kv -> kv.group(1).replace("\"", ""), // strip off double quotes
        kv -> kv.group(2).replace("\"", ""), // strip off double quotes
        (v1, v2) -> v1 // or join if needed String.join(";", v1, v2)
    ));

map.forEach((k, v) -> System.out.println(k   " -> "   v));
System.out.println("\n====\nattempt="   map.get("attempt"));

Output:

ph_no -> 111111111
some_key -> cf2fc86a
some_type -> Code
attempt -> 2
current_type -> Code

====
attempt=2

CodePudding user response:

Assuming the String structure doesn't change and attempt is the last field, you can work with the String without converting it to some POJO or Map:

public static String getAttempt(String json) {
    return json.split("\"attempt\":")[1].replaceAll("[^-?0-9] ", "");
}

Then you can do:

SString json = "[{type=Callback, output=[{name=prompt, value=InputCode}], input=[{name=IDT1, value=}]}, {type=TextOutputCallback, output=[{name=message, value={\"current_type\":\"Code\",\"info\":{\"some_key\":\"cf2fc86a\",\"some_type\":\"Code\",\"ph_no\":\"111111111\"},\"attempt\":2}}]}]";

String attempt = getAttempt(json);

System.out.pritnln(attempt);

Output:

2
  • Related