Hi there! I have a question: Is there any industry...
# serialization
j
Hi there! I have a question: Is there any industry standard library that would help me compare two JsonElements? Preferably with following features: • Ignoring JsonArray ordering (in my use-case scenario we operate on sets anyway) • Give fine-grained result, like list of jsonpaths where the differences happens
💯 1
a
How would one compare if not on ordering?
a
@Arjan van Wieringen When you serialize a set to JSON the end result would also be treated as an array in json.
a
@andries.fc I understand. But I mean: How would you compare 2 JSON arrays if you would ignore ordering? How do you match elements to recursively compare inside those elements? You'd need some sort of identifier for that. Phrased differently: How would you expect an industry standard to behave when comparing unordered sets with arbitrary elements inside?
a
You could Jackson to give you a tree element. And Jackson’s rudimentary path API to have 2 nodes (e.g. actual & expected). From there on you can traverse both in step recursively. If you end up with two nodes which are different it is mismatch. If I remember correctly Jackson even gives you a way to query the path from a child node. That can used to report the exact position of the mismatch. I would start here: https://www.baeldung.com/jackson-json-node-tree-model As well as going through the source code: https://github.com/FasterXML/jackson-core But in all honesty. I do not think it would be trivial implementation. But that is just on top of my head. I’m sure there are Unit test libraries which are doing it already. And you can also dissect their code instead of build it from scratch.: https://kotest.io/docs/assertions/json/json-overview.html
j
the biggest win of kotlinx.serialization is that we can drop the jackson completely 🙂 . and regarding comparing arrays without ordering - there are ideas, that can be applied recursively on inner objects and arrays before or during comparisons: • call
.sortedBy()
some
Comparator<JsonElement>
that works ok…ish, but it’s hard to figure out JsonPath of differences (as the list is reordered) • call
.toSet()
before comparing with
.equal()
(tricky, as
[3,1,2]
would equal
[3,1,2,1]
) • call
.groupingBy{ ... }
if you know which property is a key (or, in worst case, use
it
or
it.toString()
as key) overall, it can be done, and I’m doing it, but I had to develop (and maintain) a code that is far from my regular business, so I’d prefer to use some well-established library, if there is any 🙂
c