Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Jackson忽略使用相同类的属性_Java_Json_Jackson - Fatal编程技术网

Java Jackson忽略使用相同类的属性

Java Jackson忽略使用相同类的属性,java,json,jackson,Java,Json,Jackson,我的问题是,我想使用同一个类来反序列化和重新序列化两个不同的JSON。我试着更好地解释。 我有这些JSON: //JSON A { "flavors": [ { "id": "52415800-8b69-11e0-9b19-734f1195ff37", "name": "256 MB Server",

我的问题是,我想使用同一个类来反序列化和重新序列化两个不同的JSON。我试着更好地解释。 我有这些JSON:

//JSON A
{
    "flavors": [
        {
            "id": "52415800-8b69-11e0-9b19-734f1195ff37",
            "name": "256 MB Server",
            "ram": 256,
            "OS-FLV-DISABLED:disabled":true
            "links": [
                {
                    "rel": "self",
                    "href": "http://www.myexample.com"
                },
                {
                    "rel": "bookmark",
                    "href":"http://www.myexample.com"
                }
            ]
        },
        ...
}
//JSON B
{
    "flavors": [
        {
            "id": "52415800-8b69-11e0-9b19-734f1195ff37",
            "name": "256 MB Server",
            "links": [
                {
                    "rel": "self",
                    "href": "http://www.myexample.com"
                },
                {
                    "rel": "bookmark",
                    "href":"http://www.myexample.com"
                }
            ]
        },
        ...
}
正如您所看到的,JSON B包含JSON A的所有字段,除了“ram”和 “OS-FLV-禁用:禁用”。我使用的类如下所示:

public class Flavor {

    private String name;
    private List<Link> links;
    private int ram;
    private boolean OS_FLV_DISABLED_disabled;

//constructor and getter/setter
}

@XmlRootElement
public class GetFlavorsResponse {

    private List<Flavor> flavors;
    //constructor and getter/setter
}
现在,作为第一件事,我认为Jackson设置了Json中没有的类属性 它们的默认值,即“ram”和“false”分别为0和false “OS-FLV-禁用:禁用”。所以我把注释

@JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT)
就在风味等级之上。这是可行的,但问题是,当我收到JSON A时,其中“ram”和“OS-FLV-DISABLED:DISABLED”的值分别为0和false(可能的情况),上述过程的结果是JSON B,因为忽略了这两个字段。 我已经确定这不是解决我问题的方法,我读到一些人建议使用@JsonView或@JsonFilter,但我不知道如何在这种情况下应用这些Jackson特性。
我希望我说得很清楚,并提前感谢您的帮助。

您可以尝试的一件事是将
ram
OS\u FLV\u DISABLED
分别设置为
Integer
Boolean
类型。这样,如果json中没有这两个属性的值,那么它们将为null。并使用此注释
@JsonInclude(Include.NON_NULL)
避免序列化NULL属性。

谢谢您宝贵的建议,现在我得到了我想要的。我在flavor类上方留下了@JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT)注释,但代码仍然有效。
@JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT)