【问题标题】:jackson deserialize primitive types杰克逊反序列化原始类型
【发布时间】:2020-07-26 13:49:17
【问题描述】:

我一定是做错了...我试图通过使用 ObjecMapper 反序列化 json 来分配一个原始类型,但我无法让它工作。

json 位于一个名为“jsonTest.json”的文件中,如下所示:

{
    "simpleVariable":100
}

然后我有一个读取json的方法,其中包含以下代码:

ObjectMapper objectMapper = new ObjectMapper();
Path path = Paths.get("jsonTest.json");

// read the json into a json node
JsonNode rootNode;
try (Reader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
    // read the json file
    rootNode = objectMapper.readTree(reader); 
} catch(IOException ie) {
    rootNode = null;
    ie.printStackTrace();
}   

// now attempt to assign the value of the node to an int:
int intVar = objectMapper.readValue(rootNode, int.class);

这就是问题所在。当我尝试编译此代码时,出现以下错误:

ObjectMapper 类型中的方法 readValue(JsonParser, Class) 不适用于参数 (JsonNode, Class)。

所以很明显,我已经为 readValue 提供了一个它不能接受的 JsonParser 对象,但我还能如何反序列化一个原语?

【问题讨论】:

    标签: java json objectmapper jackson-databind


    【解决方案1】:

    试试:

    int intVar = rootNode.get("simpleVariable").asInt();
    

    【讨论】:

      【解决方案2】:

      你可以创建一个名为 JsonTest.java 的类

      public class JsonTest {
      
      
          int simpleVariable; // same name as in json file with getters and setters
      
          public int getSimpleVariable() {
              return simpleVariable;
          }
      
          public void setSimpleVariable(int simpleVariable) {
              this.simpleVariable = simpleVariable;
          }
      
      }
      

      让杰克逊负责解析值

      例子:

       public static void main(String[] args) throws IOException {
              ObjectMapper objectMapper = new ObjectMapper();
              Path path = Paths.get("jsonTest.json");
              JsonTest jsonTest=objectMapper.readValue(path.toFile(), JsonTest.class);
              int intVar = jsonTest.getSimpleVariable();
              System.out.println("simpleVariable "+intVar );
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-11-11
        • 1970-01-01
        • 2018-06-07
        • 1970-01-01
        • 2012-12-22
        • 2016-11-11
        • 1970-01-01
        相关资源
        最近更新 更多