我正在尝试从我正在进行的 API 调用中解析响应正文,但是 API 的原始创建者错误地存储了该对象。响应中的 UUID 字段应该存储为字符串,但事实并非如此。
当我在响应正文上尝试使用
json.loads()
时,它失败并出现 JSON.Decode()
错误。但是,我能够获取response.text,并且 JSON 中的某些字段仅显示为 "fieldName": 11111-22222-33333-44444
,而它应该是 "fieldName": "11111-22222-33333-44444"
。如何将这个格式不正确的对象作为 JSON 对象加载?
有没有一种简单的方法可以将这些格式不正确的对象转换为字符串?如果没有,人们会如何建议我创建自己的解析器来处理这些 UUID? UUID 可以与多个不同的键相关联,因此它是可行的,但很难对手动解析器进行硬编码。
这基本上会采用蛮力方法。在尝试解析 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"}
其他一些注意事项:
xxxx-xxxx-xxxx-xxxx
而不是 xxxxxxxx-xxxx-xxxx-xxx-xxxxxxxxxxxx
。fixUuidInJson
时都进行解析。