我如何对java中对象的属性进行排序

发布于 2025-02-01 04:02:17 字数 313 浏览 3 评论 0原文

您知道为什么在对我的应用程序进行解脱时,请更改地址对象的属性的顺序?我需要检查数据库中存储的地址等于来自前端的地址。我正在使用objectMapper将对象输入文本,以便我可以比较2个字符串,但是由于这种情况,我总是会遇到false,因为订单会随着您在下面的图片中所看到的而更改。

Do you know why when debbuging my app the order of the attributes of my address object is changed? I need to check it the address stored in the database is equal to the one coming from the frontend. I'm using objectmapper to get the object into text so the I can compare 2 strings but due this situation I always get false as the order change as you can see in the picture below.

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

白日梦 2025-02-08 04:02:17

使用新的ObjectMapper.writeValueasString()应按照您的期望为您提供字段。
正如@federico Klez Culloca所说,您应该使用对象本身进行比较。
您应该从address.getAddressString()构造address对象,或直接将address> address> address>使用a使用> A.Equals()

Using new ObjectMapper.writeValueAsString() should give you the fields in order as you expect it to.
As @Federico klez Culloca stated, you should instead use the objects themselves to compare.
You should construct an Address object from address.getAddressString() or just directly compare address to a using a.equals().

梦晓ヶ微光ヅ倾城 2025-02-08 04:02:17

您可以将字符串解析为jsonnode并进行比较。 Jackson为所有节点类型提供了equals(Object O)的覆盖。

ObjectMapper mapper = new ObjectMapper();
JsonNode actualNode = mapper.readTree(actualJson);
JsonNode expectedNode = mapper.readTree(expectedJson));
boolean matches = actualNode.equals(expectedNode);

本指南也应该有所帮助。

另一种选择是在您的自定义类中提供equals()的实现,如评论中所述。

You can parse strings to JsonNode and compare them. Jackson provides overrides of equals(Object o) for all node types.

ObjectMapper mapper = new ObjectMapper();
JsonNode actualNode = mapper.readTree(actualJson);
JsonNode expectedNode = mapper.readTree(expectedJson));
boolean matches = actualNode.equals(expectedNode);

This guide should be helpful as well.

The other option is to provide implementation of equals() in you custom class, as mentioned in comments.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文