首页 > 解决方案 > 如何正确映射 JSON 对象?

问题描述

这是我的代码:

@JsonIgnoreProperties(ignoreUnknown = true)
public class ObjectMapperJSON {
 public static void main(String[] args) throws IOException, JsonParseException, JsonMappingException {

      ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
      String jsonString = "{\"numberOFiles\":13, \"filename\":\"123.jpg\"}";

    /*  int temp = Integer.parseInt(jsonString); 
    */  ObjectMapper objectMapper = getObjectMapper();

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

      try{
         JsonBean JsonBean = mapper.readValue(jsonString, JsonBean.class);

         System.out.println(JsonBean);

         jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(JsonBean);
         //jsonString = mapper.writeValueAsString(JsonBean);

         System.out.println(jsonString);
      }
      catch (Exception e){
          e.printStackTrace();}
   }
 }

输出结果是: Filename [ filename: 123.jpg, numberOfFiles: 0 ] { "filename" : "123.jpg", "numberOfFiles" : 0

所以我的问题是为什么 numberOfFiles 的值打印为 0?调试向我显示直到最后一个 syso 的值为 13。如何正确执行此操作?

标签: java

解决方案


您的 json 字符串中有错字。更新numberOFilesnumberOfFiles.


推荐阅读