简体   繁体   中英

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

I am new to Java RESTful web services. 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:

    {
        "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.

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

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 .

You can use JAX-B annotation @XmlTransient on your attribute basicInfo .

Alternatively, when JSON-B (JSR 367) will be available (Java EE 8), you can use the @JsonbTransient or, even better, the @JsonbVisibility attribute.

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