hades
hades

Reputation: 4694

JsonNode Convert JSON to list of string

I have a json in this format:

{
    "success": 1,
    "value": "[\"1-1\",\"1-2\",\"1-3\"]"
}

The success is actually in int and value is a List of String, i want to get the value and put those elements into a List<String>. The List of String will be:

1-1
1-2
1-3

I actually wish to parse the entire json using JsonNode, but the problems that restrict me from doing so are:

  1. "[\"1-1\",\"1-2\",\"1-3\"]" is wrapped with double quotes, so it might be treated as String.
  2. Have to get rid of the backslash in the string

The following is my workaround that i tried, is there any elegant/better (It is better without regex, just parse entire json into JsonNode) way to do so?

 ObjectMapper mapper= new ObjectMapper();
 JsonNode response = mapper.readTree(payload);  //payload is the json string
 JsonNode success = response.get("success");
 JsonNode value = response.get("value");

    if (success.asBoolean()) {
        String value = value .toString();
               value = value .replaceAll("\"", "").replaceAll("\\[", "").replaceAll("\\]", "")
                    .replace("\\", "");
       return Arrays.asList(value .split(","));
    }

Upvotes: 0

Views: 12166

Answers (1)

OneCricketeer
OneCricketeer

Reputation: 191738

Have to get rid of the backslash in the string

No, you really don't.

so it might be treated as String.

It actually is, and the fact that you are viewing it as a String is the reason why the escape characters exist.

If you pass the response.get("value").toString() to an ObjectMapper parser, you should get back an array or list

How to use Jackson to deserialise an array of objects

List<String> values = MAPPER.readValue("[\"hello\", \"world\"]", new TypeReference<List<String>>(){});
System.out.println(values); // [hello, world]

The alternative, more preferred, solution is to fix the producer of the initial JSON.

Upvotes: 1

Related Questions