杰克逊对象属性变为原始

时间:2015-05-20 20:55:53

标签: java json rest jackson

我有跟随json。

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

如何反序列化为Java Pojo

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

3 个答案:

答案 0 :(得分:0)

您可以执行以下操作之一:

  • 创建代表Foo的具体类型:

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

    然后在User你会得到:

    public class User {
        private Foo foo;
    
        ...
    }
    
  • 使用Map<String, Integer>

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

如果其他来电者真的希望您拥有getFooIdsetFooId,您仍然可以提供这些方法,然后根据FooMap进行委托在你选择的选项上。只需确保使用@JsonIgnore对它们进行注释,因为它们不是真正的属性。

答案 1 :(得分:0)

这是您在构造函数中使用JsonProperty注释进行反序列化所需的内容。

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();
        }

    }
}

输出:

User fooId: 1

希望它有所帮助,

何塞路易斯

答案 2 :(得分:-1)

您可以使用非常有用的gson Google API。

首先,创建这两个类:

用户类:

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

Foo class:

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

如果您有example.json文件,请按照以下步骤反序列化

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

如果你有一个exampleJson字符串,那么按照以下反序列化

Gson gson = new Gson();
User data = gson.fromJson(exampleJson, User.class);
相关问题