有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JsonNode将JSON转换为字符串列表

我有一个json格式:

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

成功实际上是在int中,值是StringList,我想得到并将这些元素放入List<String>。字符串列表将为:

1-1
1-2
1-3

我实际上希望使用JsonNode解析整个json,但限制我这么做的问题是:

  1. "[\"1-1\",\"1-2\",\"1-3\"]"用双引号包装,因此 可能被视为字符串
  2. 必须去掉字符串中的反斜杠

下面是我尝试过的解决方法,是否有任何优雅/更好的方法(不使用正则表达式更好,只需将整个json解析为JsonNode)来做到这一点

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

共 (1) 个答案

  1. # 1 楼答案

    Have to get rid of the backslash in the string

    不,你真的不知道

    so it might be treated as String.

    实际上是这样的,而且您将它作为字符串查看是转义字符存在的原因

    如果将response.get("value").toString()传递给ObjectMapper解析器,则应返回一个数组或列表

    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]
    

    另一种更可取的解决方案是修复初始JSON的生产者