使用 Jackson 库将字符串转换为 Java 对象时主线程 com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException 出现异常

Exception in thread main com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException while converting string to Java object using Jackson library

我正在尝试从文本文件中读取一个字符串并想将其映射到一个 bean class 但我从 jackson 库中收到异常异常。

我制作了一个名为 Question.java 的 POJO,其中包含我必须从文本文件中读取的所有值。

    private String Code;
    private String QuestionCode;
    private String Description;
    private String Type;
    private String LastUpdated;

我有 main class,我从文本文件中读取字符串并尝试将其映射到问题 class

public class QuestionParser {
    
    public static void main(String[] args) throws IOException {
        
        BufferedReader reader = new BufferedReader(new FileReader("Sample.txt"));
        StringBuilder stringBuilder = new StringBuilder();
        String line = null;
        String ls = System.getProperty("line.separator");
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
            stringBuilder.append(ls);
        }
        
        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        reader.close();
        
        String content = stringBuilder.toString();
        System.out.println(content);
        String sample = content.replaceAll("\\", " ");
        
        ObjectMapper mapper = new ObjectMapper();
        
        Question question = mapper.readValue(sample, Question.class);
        System.out.println(question);
        
        
    }

}

Sample.txt看起来像

{\"Code\":\"60\",
\"QuestionCode\":\"7000\",
\"Description\":\"What is your favorite movie?\",
\"Type\":\"R\",
\"LastUpdated\":\"2015-05-21\"
}

毕竟,当我 运行 代码出现异常时

Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "Code " (class Question), not marked as ignorable (5 known properties: "type", "questionCode", "description", "code", "lastUpdated"])

  at [Source: (String)"{ "Code ": "60 ",

  "QuestionCode ": "7000 ",

  "Description ": "What is your favorite movie? ",

  "Type ": "R ",

  "LastUpdated ": "2015-05-21 "

 }

 "; line: 1, column: 13] (through reference chain: Question["Code "])

    at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:61)

    at com.fasterxml.jackson.databind.DeserializationContext.handleUnknownProperty(DeserializationContext.java:1127)

    at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1984)

    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1701)

    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1679)

    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:319)

    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:176)

    at com.fasterxml.jackson.databind.deser.DefaultDeserializationContext.readRootValue(DefaultDeserializationContext.java:322)

    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4620)

    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3575)

    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3543)

    at QuestionParser.main(QuestionParser.java:33)

解析后,您的字符串包含可变代码,例如带空格的“代码”。您应该修复替换逻辑或使用注释。

@JsonProperty("Code ")
private String Code;

您的更新造成了所有问题。 String sample = content.replaceAll("\\", " "); 正在为每个 JSON 键添加一个额外的空格。请改用以下代码:

public class QuestionParser {
    public static void main(String[] args) throws IOException {
        
        BufferedReader reader = new BufferedReader(new FileReader("Sample.txt"));
        StringBuilder stringBuilder = new StringBuilder();
        String line = null;
        String ls = System.getProperty("line.separator");
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
            stringBuilder.append(ls);
        }
        
        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        reader.close();
        
        String content = stringBuilder.toString();
        System.out.println(content);
        String sample = content.replaceAll("\\", "");
        
        ObjectMapper mapper = new ObjectMapper();
        
        Question question = mapper.readValue(sample, Question.class);
        System.out.println(question);    
    }
}

注意更改后的行:String sample = content.replaceAll("\\", "");.

此外,正如@Jens 已经提到的,遵循 Java 约定并遵循 Java 属性 名称的驼峰式命名法。话虽如此,也请将您的 Question 更改为:

public class Question {
    private String code;
    private String questionCode;
    private String description;
    private String type;
    private String lastUpdated;

    //getters & setters
}

最后,您还需要调整您的JSON如下:

{\"code\":\"60\",
\"questionCode\":\"7000\",
\"description\":\"What is your favorite movie?\",
\"type\":\"R\",
\"lastUpdated\":\"2015-05-21\"
}

更新

假设您无法更改您尝试读取的 JSON 文件,您需要在 Question class 中使用 @JsonProperty 注释来“粘合”属性在一起。在这种情况下,JSON 仍然看起来像您在问题中添加的那样:

{\"Code\":\"60\",
\"QuestionCode\":\"7000\",
\"Description\":\"What is your favorite movie?\",
\"Type\":\"R\",
\"LastUpdated\":\"2015-05-21\"
}

但是你的 Question class 会有一堆 @JsonProperty 注释(你可以在 https://fasterxml.github.io/jackson-annotations/javadoc/2.8/com/fasterxml/jackson/annotation/JsonProperty.html 阅读更多相关信息):

public class Question {
    @JsonProperty("Code")
    private String code;

    @JsonProperty("QuestionCode")
    private String questionCode;

    @JsonProperty("Description")
    private String description;

    @JsonProperty("Type")
    private String type;

    @JsonProperty("LastUpdated")
    private String lastUpdated;

    //getters & setters
}

您对文件的定义和读取不正确。 JSON不是行分隔的,所以不要把它读成行

JSON 应该是这样的,例如,没有反斜杠...

(理想情况下,文件扩展名也应为 .json,但无关紧要,除了您的文本编辑器)

{
  "Code": "60",
  "QuestionCode":"7000"
}

此外,Java字段名称应注释或与JSON字段完全匹配; Java 字段应为小写。如果您想使用整数或除字符串

以外的其他数据类型,您还可以删除 JSON 值中的引号
public class Question {

 public Question() { }

 @JsonProperty("Code")
 private String code;

 // getters and setters
}

然后就可以直接用ObjectMapper打开了

ObjectMapper om = new ObjectMapper();
// File should be in `src/main/resources` folder of a Java project
InputStream is = QuestionParser.class.getResourceAsStream("/questions.json");
Question q = om.readValue(is, Question.class);