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.
Verification token is a VerifData object serialized into a String and then hashed and encrypted.
class VerifData { int prop1; int prop2; }
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);
But it seems that each time the application container is started, the order of properties being mapped into a string by ObjectMapper changes.
Ex: one time it would be
{"prop1":12345,"prop2":67890}
and another time it would be
{"prop2":67890,"prop1":12345}
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.
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.
Any error or exception? The JSON RFC (RFC 4627) says that order of object members does not matter.
The @JsonPropertyOrder is an annotation to be used at the class-level. It takes as property a list of fields that defines the order in which fields can appear in the string resulting from the object JSON serialization.
You cannot change the order if you are using the JSON function. It will always be alphabetical.
As seen above in the JSONResponse, since object is an unordered set of name/value pairts, so JSONObject isn't preserving the order of my object's name/value pairs.
The annotations are useful, but can be a pain to apply everywhere. You can configure your whole ObjectMapper
to work this way with
Current Jackson versions:
objectMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true)
Older Jackson versions:
objectMapper.configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY, true);
From the Jackson Annotations documentation:
// 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With