JSON field - Parse String to Int

jackson, java, json

Solution

You don't need to.

Jackson is smart enough to convert a JSON string to a numerical value if the target field is numerical.

It's not obvious what the leading `0` is meant to represent, but Jackson will simply ignore it.

Also, if your field name is different in Java, you'll need `@JsonProperty("theJsonName")`.

public class Jackson {
    public static void main(String[] args) throws Exception {
        String json = "{\"userId\": \"021\", \"userAge\": 99}";
        ObjectMapper mapper = new ObjectMapper();
        User user = mapper.readValue(json, User.class);
        System.out.println(user.userId);
    }
}

class User {
    int userId;
    int userAge;
    public void setUserId(int userId) {
        this.userId = userId;
    }
    public void setUserAge(int userAge) {
        this.userAge = userAge;
    }
}

prints

21

Problem

Have a relatively simple (I think) issue, but being a novice to JSON cannot seem to find a neat solution. I have an Entity object with Id field as type Integer. However, the incoming Json data to be mapped has the id as a string. With this a straightforward map does not seem to be possible. Is there a way to change the string data in the JSON to an integer, before mapping? Example Json data ``` {"Id": "021", "userAge": 99} ``` Example Entity ``` @Entity public class User{ @id int userId; int userAge; } ``` Many Thanks.

Original source