简体   繁体   中英

Extracting values from key-value pair seperated by colon

I have a String that is something like:

Key1: value1
Key2: value2
Key3: value3
Time: Thursday, Dec 9:09:10

{
"JRandomKey1":"RandomValue",
"RandomKey2":"RandomValue"
}

I do not want the JSON on the bottom half .

I want to be able to extract the Keys (Key1, Key2, Key3, Time) and their values (values are ordinary english sentences) that is followed by the colon. Anyone have any thoughts on a good way to go about this? The time also has colons in it and the JSON object at the bottom too has colons.

Thankyou

Assuming that you do not have strings with { as a character in it and that the JSON is never broken. Here is an approach without any libraries:

// split the string on new line
String[] arr = s.split("[\\r\\n]+");

// store key value pairs
Map<String, String> map = new HashMap<>();

for (int i = 0; i < arr.length; i++) {
    // start ignoring JSON
    if (arr[i].contains("{")) {
        for (; i < arr.length; i++) {
            if (arr[i].contains("}")) {
                i++;
                // end ignoring JSON
                break;
            }
        }
    } else {
        String a = arr[i];
        map.put(a.substring(0, a.indexOf(":")), a.substring(a.indexOf(":") + 1));
    }
}

System.out.println(map);
// {Key2= value2, Key1= value1, Key3= value3, Time= Thursday, Dec 9:09:10}

Or, you could sanitize the string beforehand and use Java8 features:

while (s.contains("{") && s.contains("}"))
    s = s.substring(0, s.indexOf("{")) + s.substring(s.indexOf("}") + 1);


Map<String, String> map = Arrays.stream(s.split("[\\r\\n]+")).collect(Collectors
    .toMap(a -> a.substring(0, a.indexOf(":")), a -> a.substring(a.indexOf(":") + 1),
        (a1, b) -> b));

Note : this won't work for nested json objects or json arrays. But you get the idea on how you can modify the code to accommodate that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM