How does the Jackson mapper know what field in each Json object to assign to a class object?

前端 未结 1 446
盖世英雄少女心
盖世英雄少女心 2020-12-08 05:35

Let\'s say I have a Json object like this:

{
    \"name\": \"Bob Dole\",
    \"company\": \"Bob Dole Industries\",
    \"phone\": {
        \"work\": \"123-4         


        
相关标签:
1条回答
  • 2020-12-08 05:51

    Without Annotations:

    Without any annotations, it does what is called POJO mapping, it just uses reflection on the instance members and uses some rules about how to map the keys in the json to the names of the instance members. *note: it works on private members as well as public or package protected as well

    If it doesn't match the names of the instance members, then it starts trying to match the getXXX and setXXX methods, if it doesn't match anything then it gives up.

    With Annotations:

    It uses the metadata supplied by the annotations to do the mapping and conversions.

    It is always better to explicitly use the annotations when you have the source to add them to, then there is no guess work on what gets mapped to what.

    Remember explicit is always better than implicit!

    This is all well documented on the WIKI:

    Mapping and Annotations

    JSON Schema:

    I am creating JSON Schema definitions for all my new projects now to document what is and isn't valid JSON according to the schema rules engine. It is a great way to document your data structures and eliminate parsing errors.

    0 讨论(0)
提交回复
热议问题