简体   繁体   中英

jackson object property into primitive

I have the follow json.

{
   foo:{
      id:1
   },
   name:'Albert',
   age: 32
}

How can I deserialize to Java Pojo

public class User {
    private int fooId;
    private String name;
    private int age;
}

You can do one of the following:

  • Create a concrete type representing Foo :

     public class Foo { private int id; ... } 

    Then in User you would have:

     public class User { private Foo foo; ... } 
  • Use a Map<String, Integer> :

     public class User { private Map<String, Integer> foo; ... } 

If other callers are really expecting you to have a getFooId and a setFooId , you can still provide these methods and then either delegate to Foo or the Map depending on the option you choose. Just make sure that you annotate these with @JsonIgnore since they aren't real properties.

This is what you need to deserialize, using the JsonProperty annotations in your constructor.

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class User {

    private int fooId;
    private String name;
    private int age;

    public int getFooId() {
        return fooId;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public User(@JsonProperty("age") Integer age, @JsonProperty("name") String name,
                @JsonProperty("foo") JsonNode foo) {
        this.age = age;
        this.name = name;
        this.fooId = foo.path("id").asInt();
    }

    public static void main(String[] args) {

        ObjectMapper objectMapper = new ObjectMapper();

        String json = "{\"foo\":{\"id\":1}, \"name\":\"Albert\", \"age\": 32}" ;
        try {
            User user = objectMapper.readValue(json, User.class);

            System.out.print("User fooId: " + user.getFooId());

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Output:

User fooId: 1

Hope it helps,

Jose Luis

You can use a very helpful gson google API.

First of all, create these two classes:

User class:

public class User{
    Foo foo;
    String name;
    int age;
    //getters and setters
} 

Foo class:

public class Foo{
    int id;
    //getters and setters
}

If you have a example.json file then deserialize it as follow

Gson gson = new Gson();
User data = gson.fromJson(new BufferedReader(new FileReader(
        "example.json")), new TypeToken<User>() {
}.getType());

If you have a exampleJson String then deserialize it as follow

Gson gson = new Gson();
User data = gson.fromJson(exampleJson, User.class);

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