Skip to content

Commit

Permalink
Fix: ToJsonEncoder keeps order fields during encoding map
Browse files Browse the repository at this point in the history
  • Loading branch information
lciolecki committed Nov 26, 2024
1 parent 8a6c1cf commit d048e74
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ import pl.touk.nussknacker.engine.api.DisplayJson
import pl.touk.nussknacker.engine.util.Implicits._

import java.util.ServiceLoader

import java.util.UUID
import scala.collection.SeqMap
import scala.collection.immutable.ListMap
import scala.jdk.CollectionConverters._

object ToJsonEncoder {
Expand Down Expand Up @@ -88,9 +89,13 @@ case class ToJsonEncoder(
// TODO: make encoder aware of NU Types to encode things like multiset differently. Right now its handled by calling
// toString on keys.
private def encodeMap(map: Map[_, _]) = {
val mapWithStringKeys = map.view.map { case (k, v) =>
k.toString -> v
}.toMap
// TODO: Switch to SeqMap after removing support for Scala 2.12
val mapWithStringKeys = ListMap.from(
map.toList.map { case (k, v) =>
k.toString -> v
}
)

fromFields(mapWithStringKeys.mapValuesNow(encode))
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import pl.touk.nussknacker.test.ClassLoaderWithServices
import java.time._
import java.util
import java.util.UUID
import scala.collection.SeqMap
import scala.collection.immutable.{ListMap, ListSet}

class ToJsonEncoderSpec extends AnyFunSpec with Matchers {
Expand Down Expand Up @@ -101,6 +102,24 @@ class ToJsonEncoderSpec extends AnyFunSpec with Matchers {

}

it("should convert map to json and keep order of keys") {
val map = ListMap(
"intNumber" -> 42,
"floatNumber" -> 42.42,
"someTimestamp" -> 1496930555793L,
"someString" -> "hello",
"booleanValue" -> true
)

encoder.encode(map) shouldBe Json.obj(
"intNumber" -> fromInt(42),
"floatNumber" -> fromFloatOrNull(42.42f),
"someTimestamp" -> fromLong(1496930555793L),
"someString" -> fromString("hello"),
"booleanValue" -> fromBoolean(true),
)
}

}

class CustomJsonEncoderCustomisation1 extends ToJsonEncoderCustomisation {
Expand Down

0 comments on commit d048e74

Please sign in to comment.