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

查看:6976
本文介绍了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}

另一次是

and another time it would be

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

因此,如果客户端已将VerifData实例序列化为第一个String,则即使它是正确的,也有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 Annotations文档

// 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天全站免登陆