Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON field - Parse String to Int

Tags:

java

json

jackson

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.

like image 332
Php Pete Avatar asked Oct 19 '25 05:10

Php Pete


1 Answers

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
like image 67
Sotirios Delimanolis Avatar answered Oct 21 '25 18:10

Sotirios Delimanolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!