4

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.

0

2 Answers 2

8

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
Sign up to request clarification or add additional context in comments.

Comments

1

You can write a custom jackson deserializer to cope with this behaviour. There's an good blog post on this topic here.

public class ItemDeserializer extends JsonDeserializer<Item> {

    @Override
    public Item deserialize(JsonParser jp, DeserializationContext ctxt) 
      throws IOException, JsonProcessingException {
        JsonNode node = jp.getCodec().readTree(jp);
        int id = Integer.parseInt(node.get("userId").asText());
        int userAge = (Integer) ((IntNode) node.get("userAge")).numberValue();

        return new Item(id, userAge);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.