Json4s Custom Serializer with Unordered Fields

In the json4s readme example https://github.com/json4s/json4s#serializing-non-supported-types , the match only works if the fields are ordered {"start": 0, "end": 0} . If the start and end fields are reversed, then the match does not work. Is there anyway to write the match below so that the ordering of the JSON fields does not matter?

case JObject(JField("start", JInt(s)) :: JField("end", JInt(e)) :: Nil) 
+6
source share
2 answers

I have not used this library, so I'm not sure if this is the right approach: (I came up with this by spending a couple of minutes on the documents)

 class IntervalSerializer extends CustomSerializer[Interval](format => ( { case x: JObject => x.obj.sortBy { case (k,_) => k } match { case JField("end", JInt(e)) :: JField("start", JInt(s)) :: Nil => new Interval(start = s.longValue(), end = e.longValue()) } }, { case x: Interval => JObject(JField("start", JInt(BigInt(x.startTime))) :: JField("end", JInt(BigInt(x.endTime))) :: Nil) } )) 

The idea is to sort the fields alphabetically and then create an Interval class.

+4
source

I had a different but related problem that made me open the "extract" function in json4s. It solves the order problem.

 case x: JObject => Interval((x \ "start").extract[Int],(x \ "end").extract[Int]) 

If you need a more attractive example, you can check out this github ticket .

+3
source

Source: https://habr.com/ru/post/972794/


All Articles