gpt4 book ai didi

当值包含双引号时,Java jackson ObjectMapper 失败?

转载 作者:太空宇宙 更新时间:2023-11-04 11:05:24 24 4
gpt4 key购买 nike

我有java字符串(包含json对象)

{"Attribute_1":""test"","Attribute_2":"100"}

当我转换为 java 对象 MyCustomClass 时,由于 test 周围有双引号,我收到运行时错误。我不知道如何转义里面的双引号json属性值

ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(requestData, MyCustomClass.class);

错误是

com.fasterxml.jackson.core.JsonParseException: Unexpected character ('t' (code 116)): was expecting comma to separate OBJECT entries
at [Source: {"Attribute_1":""test"","Attribute_2":"100"} line: 1, column: 12]
at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1419)
at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:508)
at com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar(ParserMinimalBase.java:437)
at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._skipComma(ReaderBasedJsonParser.java:1795)

这不是 How to escape double quotes in JSON 的重复项偶然,因为这是显示问题

最佳答案

您错误地转义了它。正确的方法是您必须相应地提供 json,以便编译器可以转义 json 值的“”。将 json 字符串写为:

String json = "{\"c\" : \"Hello \"Test\" there is a problem\"}";

示例测试代码:

public static void main(String[] args) throws Exception {
TypeReference<HashMap<String, String>> tr = new TypeReference<HashMap<String, String>>() {
};
String json = "{\"c\" : \"Hello \"Test\" there is a problem\"}";
System.out.println(new ObjectMapper().readValue(json, tr));
}

关于当值包含双引号时,Java jackson ObjectMapper 失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46525369/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com