Jackson ObjectMapper - 指定对象属性的序列化顺序 [英] Jackson ObjectMapper - specify serialization order of object properties

查看:42
本文介绍了Jackson ObjectMapper - 指定对象属性的序列化顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实施 RESTful Web 服务,其中用户必须随请求一起发送签名验证令牌,以便我可以确保请求没有被中间人篡改.我目前的实现如下.

I'm implementing a RESTful web service where user has to send a signed verification token along with the request so that I could ensure that the request has not been tampered by a middle man. My current implementation is as follows.

验证令牌是一个 VerifData 对象,序列化为字符串,然后散列和加密.

Verification token is a VerifData object serialized into a String and then hashed and encrypted.

class VerifData {
    int prop1;
    int prop2;
}

在我的服务中,我将要序列化的数据放入 VerifData 的实例中,然后使用 Jackson ObjectMapper 将其序列化,并与验证令牌一起传递给验证引擎.

In my service, I put data to be serialized into an instance of VerifData and then serialize it using Jackson ObjectMapper and passed along to the verification engine along with the verification token.

VerfiData verifData = new VerifData(12345, 67890);
ObjectMapper mapper = new ObjectMapper();
String verifCodeGenerated = mapper.writeValueAsString(verifData);

但似乎每次启动应用程序容器时,ObjectMapper 映射到字符串的属性顺序都会发生变化.

But it seems that each time the application container is started, the order of properties being mapped into a string by ObjectMapper changes.

例如:有一次是

{"prop1":12345,"prop2":67890}

还有一次是

{"prop2":67890,"prop1":12345}

因此,如果客户端将 VerifData 实例序列化为第一个字符串,即使它是正确的,也有 50% 的机会失败.

So if client has serialized the VerifData instance as into the first String, there is 50% chance of it being failed even though it is correct.

有没有办法解决这个问题?我可以通过 ObjectMapper 指定要映射的属性的顺序(如升序)吗?或者有没有其他方法可以最好地实施此验证步骤.客户端和服务器实现都是由我开发的.我使用 Java Security API 进行签名和验证.

Is there a way to get around this? Can I specify the order of properties to map by ObjectMapper (like in ascending order)? Or is there any other way to best implement this verification step. Both client and server implementations are developed by me. I use Java Security API for signing and verifying.

推荐答案

来自 Jackson 注释文档:

// ensure that "id" and "name" are output before other properties
@JsonPropertyOrder({ "id", "name" })

// order any properties that don't have explicit setting using alphabetic order
@JsonPropertyOrder(alphabetic=true)

这篇关于Jackson ObjectMapper - 指定对象属性的序列化顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆