解析未存储为正确 JSON 的 JSON 字段

问题描述 投票:0回答:1

我正在尝试从我正在进行的 API 调用中解析响应正文,但是 API 的原始创建者错误地存储了该对象。响应中的 UUID 字段应该存储为字符串,但事实并非如此。

当我在响应正文上尝试使用

json.loads()
时,它失败并出现
JSON.Decode()
错误。但是,我能够获取response.text,并且 JSON 中的某些字段仅显示为
"fieldName": 11111-22222-33333-44444
,而它应该是
"fieldName": "11111-22222-33333-44444"
。如何将这个格式不正确的对象作为 JSON 对象加载?

有没有一种简单的方法可以将这些格式不正确的对象转换为字符串?如果没有,人们会如何建议我创建自己的解析器来处理这些 UUID? UUID 可以与多个不同的键相关联,因此它是可行的,但很难对手动解析器进行硬编码。

java json rest uuid
1个回答
0
投票

这基本上会采用蛮力方法。在尝试解析 json 之前,您需要通过如下所示的转换函数运行响应 json。

private String fixUuidInJson(String json)
{
    String regex = "(\"?[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}\"?)";

    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(json);

    System.out.println(String.format("Bad Json: %s", json));

    while (matcher.find())
    {
        String match = matcher.group(1);
        if (!match.startsWith("\""))
        {
            json = json.replace(match, String.format("\"%s\"", match));
        }
    }

    System.out.println(String.format("Fixed Json: %s", json));

    return json;
}

然后我们可以调用它并查看响应:

String fixedJson = fixUuidInJson("{\"fieldName1\": 11111111-2222-3333-4444-555555555555, \"fieldName2\": 22222222-3333-4444-5555-666666666666, \"foo\": \"bar\"}");

输出如下:

Bad Json: {"fieldName1": 11111111-2222-3333-4444-555555555555, "fieldName2": 22222222-3333-4444-5555-666666666666, "foo": "bar"}
Fixed Json: {"fieldName1": "11111111-2222-3333-4444-555555555555", "fieldName2": "22222222-3333-4444-5555-666666666666", "foo": "bar"}

其他一些注意事项:

  • 您示例中的 UUID 不是正确的 UUID 格式。如果您的 API 响应实际上并未发送回 UUID 格式的值,那么您可能需要修改正则表达式以考虑
    xxxx-xxxx-xxxx-xxxx
    而不是
    xxxxxxxx-xxxx-xxxx-xxx-xxxxxxxxxxxx
  • 该模式应该在某处静态定义,这样就不必在每次调用
    fixUuidInJson
    时都进行解析。
  • 打印线仅用于演示目的,应在生产中删除。
  • 如果 UUID 前面没有双引号,则该函数仅添加双引号。它并不能验证最后没有一个。这假设 API 永远不会返回末尾仅带有双引号的 UUID。
© www.soinside.com 2019 - 2024. All rights reserved.