简体   繁体   中英

jackson deserialize primitive types

I must be doing this wrong... I'm trying to assign a single primitive type by deserialising json with ObjecMapper but I can't get it to work.

The json is in a file called "jsonTest.json" which looks like this:

{
    "simpleVariable":100
}

I then have a method for reading json with the following code in it:

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);

And herein lies the problem. When I try to compile this code I get the following error:

The method readValue(JsonParser, Class) in the type ObjectMapper is not applicable for the arguments (JsonNode, Class).

So obviously I've fed readValue with a JsonParser object which it can't accept but how else would I deserialise a primitive?

Try:

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

you can make class named 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;
    }

}

and let jackson take care of parsing the values

Example:

 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 );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM