java - 如何根据方法忽略字段?

标签 java json spring annotations jackson

如何根据方法忽略字段?

我有一个关于 Spring Jackson 注释的问题。

我有一个模型类。代码:

public class Tenant{
@JsonIgnore
private String id;

@JsonProperty("id")
@JsonDeserialize(using = StringValueDeserializer.class)
private String idSIMC;

@JsonProperty("name")
private String displayName;

@JsonProperty("description")
private String description;

@JsonProperty("default")
private boolean def;

@JsonProperty("geoLoc")
@JsonDeserialize(using = GeoLocationIdNameDeserializer.class)
private GeoLocation geoLoc;

@JsonProperty("asnId")
private String asnId;

@JsonProperty("devices")
@JsonDeserialize(using = StringArrayIdDeserializer.class)
private List<String> tempDevice = Collections.synchronizedList(new ArrayList<>());


@JsonIgnore 
@JsonProperty("devices") // <-- I need to add this
private List<Device> devices = Collections.synchronizedList(new ArrayList());

//getters and setters...
}

现在是我的问题。我在类上方有方法#1 实例,并写入设备的 tempDevice ID。 method#2 从服务器获取所有设备并按 tempDevice 过滤它们(我需要这样做)我可以注释(或其他)我的字段以根据调用的方法被忽略为 Json 对象吗?

方法#1

public List<Tenant> getTenantsFromServer() {
    SSLVerification.disableSslVerification();
    ArrayList<Tenant> tenants = new ArrayList<>(0);

    String[] ids = getTenantIds();


    for(int i=0; i<ids.length; i++){
        ResponseEntity<ReturnUnique<Tenant>> result = getRestTemplate().exchange(getUrl() + SIEMCommands.ZONE_GET_ZONE + "?id=" + ids[i],
                HttpMethod.GET, new HttpEntity(getHeader()), new ParameterizedTypeReference<ReturnUnique<Tenant>>(){});
        Tenant newTenant = result.getBody().getValue();
        newTenant.setParentNode(this);

        newTenant.generateId();
        tenants.add(newTenant);
    }
    return tenants;
}

在这个方法中,我有一个关键的“设备”,其中存储了ID。在方法#2中,另一个json也有“devices”键,但有另一个日期。(名称,ip等)当我执行此方法时,我应该将所有内容存储在设备列表中。

第一个方法#1中使用的 JSON

{"return": {
"asnId": 0,
"default": false,
"description": "",
"devices": [
    {"id": 144121785900597248},
    {"id": 144121785917374464},
    {"id": 144121785934151680}
],
"geoLoc": {
    "id": {"value": 0},
    "name": ""
},
"id": {"value": 1},
"name": "HA_Zone"
}}

设备值写入tempDevice;

方法#2 使用此 JSON

"devices": [{
                "CRuleRight": true,
                "FTestRight": true,
                "adRight": true,
                "addDeleteRight": false,
                "children": [],
                "clientCount": 0,
                "clientStatus": "0",
                "clientVipsInSync": false,
                "deviceActionRight": true,
                "deviceDisabled": false,
                "elmFile": false,
                "elmHasSAN": false,
                "eventRight": true,
                "hostname": "",
                "ipAddress": "172.28.60.17",
                "ipsID": "144121785950928896",
                "ipsRight": true,
                "name": "ASA Admin CTX Site 2",
                "parent": false,
                "polRight": true,
                "protocol": "gsyslog",
                "reportRight": true,
                "status": "6",
                "statusAck": "0",
                "tpcCollector": "syslog",
                "tpcType": "278",
                "type": "VIPS",
                "viewRight": true,
                "vipsEnabled": true,
                "vipsID": "49",
                "vipsInSync": false
            },
            {
                "CRuleRight": true,
                "FTestRight": true,
                "adRight": true,
                "addDeleteRight": false,
                "children": [],
                "clientCount": 0,
                "clientStatus": "0",
                "clientVipsInSync": false,
                "deviceActionRight": true,
                "deviceDisabled": false,
                "elmFile": false,
                "elmHasSAN": false,
                "eventRight": true,
                "hostname": "",
                "ipAddress": "172.28.13.10",
                "ipsID": "144121785179176960",
                "ipsRight": true,
                "name": "ASA-VPN-DC1",
                "parent": false,
                "polRight": true,
                "protocol": "gsyslog",
                "reportRight": true,
                "status": "0",
                "statusAck": "0",
                "tpcCollector": "syslog",
                "tpcType": "278",
                "type": "VIPS",
                "viewRight": true,
                "vipsEnabled": true,
                "vipsID": "3",
                "vipsInSync": false
            }
        }]

这个日期我必须在设备中写入

最佳答案

如果我理解正确,您正在寻找一种方法将具有相同属性名称的 2 个不同 json 数据类型反序列化为不同情况下的对象。如果是这种情况,建议使用 JacksonMixInAnnotations来自@Thomas 应该可以。 JacksonMixInAnnotations 可以提供一种在运行时将另一个类(称为混合类)的注释添加到目标类的方法。

就您而言,您可以保留 tempDevicedevices 而不使用 Jackson 注释,如下所示:

public class Tenant {

    private List<String> tempDevice;

    private List<Device> devices;

}

并声明 2 个混合类:

abstract class TempDeviceMixIn {
    @JsonProperty("devices")
    private List<String> tempDevice;
}

abstract class DeviceMixIn {
    @JsonProperty("devices")
    private List<Device> devices;
}

当您需要反序列化具有devices字符串属性的json字符串时,您可以添加混合类注释,例如:

ObjectMapper mapper = new ObjectMapper();
mapper.addMixInAnnotations(Tenant.class, TempDeviceMixIn.class);
Tenant tenant = mapper.readValue(json, Tenant.class);

使用 devices 对象属性反序列化 json 字符串类似。

当您使用 RestTemplate 时,您将需要一个 MappingJacksonHttpMessageConverter 和您的 ObjectMapper

关于java - 如何根据方法忽略字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38436154/

相关文章:

java - Spring 数据休息 : Foreign key is update with null after post call in one to many relationship

java - 如何在基于 Netbeans 平台的 Java 应用程序中创建自动备份功能?

c# - 在 Web Api 项目中读取 CollectionJson 内容

java - 不可变/多态 POJO <-> 使用 Jackson 进行 JSON 序列化

javascript - 谷歌APIgapi.client.request不工作

java - intellij 不存在类型变量 R 的实例,因此 Flux<R> 符合 Publisher<?扩展 DataBuffer> 问题

java - 错误无法检测 ServletContainerInitializers Tomcat 8

java - 连接MySql数据库时BIRT报错

java - Spring mvc :resource not finding *. ico 文件

java - 如何管理/停止 spring 4 ConcurrentTaskScheduler