简体   繁体   English

如何在JSON响应中忽略(/隐藏)类的属性

[英]How to ignore(/hide) attributes of class in JSON response

I am new to Java RESTful web services. 我是Java RESTful Web服务的新手。 I have classes structure as following: 我有如下的类结构:

    class BaseClass{
        String basicInfo; 
    }

    class DataClass extends BaseClass{
        String id;  
    }   

    class DataList extends BaseClass{
        List<DataClass> dataList;
    }

when I get DataList class as Response of web-service, I get it in following format: 当我将DataList类作为Web服务的响应时,我以以下格式获取它:

    {
        "basicInfo" : "Mandetory",
        "dataList"  : [
                {
                    "basicInfo" : "Optional",
                    "id" : "I_1001"                 
                },
                {
                    "basicInfo" : "Mandetory",
                    "id" : "I_1002"
                }
        ]

    }

But I want to ignore "basicInfo" attribute in every Data Object of dataList. 但是我想忽略dataList的每个Data Object中的“ basicInfo”属性。

ex. 恩。

{
        "basicInfo" : "Mandetory",
        "dataList"  : [
                {
                    "id" : "I_1001"                 
                },
                {
                    "id" : "I_1002"
                }
        ]

    }

Is there any way through which I could ignore these attributes(using annotations)? 有什么办法可以忽略这些属性(使用注释)?

Note : I can't change the class structures. 注意:我无法更改类结构。

@JsonIgnore @JsonIgnore

the above is the annotation you require. 以上是您需要的注释。 for more variations of this you can go through the following link . 要获得更多的变化,您可以通过以下链接 add the above annotation to the fields which you wish to ignore in your transfer object and it will be ignore when parsing. 将上面的注释添加到您要在传输对象中忽略的字段,解析时将忽略它。 Since you haven't mentioned which library you are using to work with json, i have answered your question using Jackson Library . 既然您没有提到要使用哪个库来处理json,我已经使用Jackson Library回答了您的问题。

You can use JAX-B annotation @XmlTransient on your attribute basicInfo . 您可以使用JAX-B注解@XmlTransient你的属性basicInfo

Alternatively, when JSON-B (JSR 367) will be available (Java EE 8), you can use the @JsonbTransient or, even better, the @JsonbVisibility attribute. 另外,当JSON-B(JSR 367)可用(Java EE 8)时,您可以使用@JsonbTransient或更好的@JsonbVisibility属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM