plokhotnyuk/jsoniter-scala
حول
وحدات ماكرو Scala لتوليد برامج ترميز JSON آمنة وفائقة السرعة أثناء الترجمة، مع مُسرِّع circe.
أدوات التطويرما يمكنك فعله
- Parses JSON from String, Array[Byte], java.nio.ByteBuffer, and java.io.InputStream/java.io.FileInputStream
- Serializes JSON to String, Array[Byte], java.nio.ByteBuffer, and java.io.OutputStream/java.io.FileOutputStream
- Parses from and serializes to a part of Array[Byte] or java.nio.ByteBuffer, set by a position and a limit
- Parses streams of JSON values and JSON arrays from java.io.InputStream/java.io.FileInputStream without holding all input and parsed values in memory
النمو المقاس للنجوم
- خلال 24 ساعة
- ٠
- خلال 7 أيام
- +٢
- خلال 15 يومًا
- +٢
- خلال شهر
- جارٍ جمع السجل
تغيّر صافي النجوم خلال فترات متداخلة، وليس مجموعًا يوميًا. تبقى القياسات المفقودة فارغة. النجوم تقيس الاهتمام لا جودة البرمجيات.
README.md
الأصلjsoniter-scala
Scala macros for compile-time generation of safe and ultra-fast JSON codecs.
Latest results of benchmarks on JVMs that compare parsing and
serialization performance of jsoniter-scala with: borer,
circe,
circe with jsoniter-scala booster,
fory-json-scala,
jackson-module-scala,
json4s-jackson,
json4s-native,
play-json,
play-json with jsoniter-scala booster,
smithy4s-json,
spray-json, uPickle,
weePickle, zio-blocks,
zio-json, zio-schema-json
libraries compiled by Scala 3.9.0 with -opt -opt-inline:**,!java.** options for optimization and inlining
using different JDK and GraalVM versions on Intel® Core™ Ultra 9 285K CPU @ 3.7GHz (max 5.7GHz, 200S Boost),
RAM 64Gb DDR5-6400, Ubuntu Server 25.04 (Linux 7.0), and latest versions of JDK 17/21/25/28ea,
GraalVM Community JDK 17/21/25, and GraalVM JDK 17/21/25*.
Latest results of benchmarks on browsers that
compare performance of jsoniter-scala with: circe,
circe with jsoniter-scala booster,
play-json,
play-json with jsoniter-scala booster,
smithy4s-json,
uPickle, zio-blocks,
zio-json, and zio-schema-json
libraries compiled by Scala 3.9.0 with -opt -opt-inline:**,!java.** options for optimization and inlining
using Scala.js 1.23.0 to ES 2021 with Closure compiler v20240317 optimizations applied on
Apple M5 Pro CPU @ 3.0GHz (max 4.6GHz, 18-cores), RAM 64Gb LPDDR5X-9600, macOS (Golden Gate 27.2)
and latest versions of web browsers.
Contents
Acknowledgments
This library started from macros that reused the reader and writer of jsoniter (json-iterator) for Java, and then evolved its own core for parsing and serialization.
The idea to generate codecs by Scala macros and its main details came from Kryo Macros (originally developed by Alexander Nemish), adapted for JSON.
Other Scala macros features came from AVSystem Commons and magnolia.
Ideas for the most efficient parsing and serialization of java.time.* values came from the java.time.OffsetDateTime
implementation of DSL-JSON.
Projects and a blog post behind the safety and performance of parsing and serialization of numbers:
- XJB - the most efficient and concise serialization of doubles and floats, based on the Schubfach algorithm and other state-of-the-art algorithms
- rust-lexical - the most efficient precise parsing of floats and doubles
- big-math - parsing of
BigIntandBigDecimalvalues withO(n^1.5)complexity instead ofO(n^2)of Java's implementations, wherenis the number of digits - James Anhalt's algorithm - the ingenious printing of integers as decimal strings
Projects and a blog post behind SWAR tricks for the JVM:
- borer - fast parsing of JSON strings by 8-byte words
- simdjson - fast checking of strings for digits by 8-byte words
- FastDoubleParser - fast parsing of numbers by 8-byte words
- Johnny Lee's article - fast conversion of time strings to seconds
Big kudos to all contributors:
A huge thank you to my GitHub Sponsors for their support, and to JetBrains for providing excellent tooling that powers this open-source work!
Goals
- Safety: validate parsed values fail-fast with clear error reports, limit suboptimal data structures with safe defaults against DoS attacks, and instantiate only a fixed set of classes during parsing against RCE attacks
- Correctness: support the latest JSON format (RFC-8259), never replace illegally encoded characters of strings with placeholders, round too long JSON numbers half-even to their binary representation, and serialize floats and doubles to the shortest text without losing precision
- Speed: parse and serialize JSON directly between UTF-8 bytes and your data structures, crazily fast: without runtime reflection, runtime code generation, intermediate ASTs, or hash maps, and with minimal allocations and copying
- Productivity: derive codecs for complex types recursively with a one-line macro at compile-time to minimize
runtime issues, print generated sources to inspect their safety and correctness or to start custom codecs from them,
and prohibit serialization of
nullvalues and parsing to them in generated codecs - Ergonomics: provide the safest defaults for common usage, easily changed by compile-time and runtime configurations, annotations, and implicits, pretty print JSON on demand, and show hex dumps in error messages to speed up viewing of the error context
Features and limitations
Features:
- Parses JSON from
String,Array[Byte],java.nio.ByteBuffer, andjava.io.InputStream/java.io.FileInputStream - Serializes JSON to
String,Array[Byte],java.nio.ByteBuffer, andjava.io.OutputStream/java.io.FileOutputStream - Parses from and serializes to a part of
Array[Byte]orjava.nio.ByteBuffer, set by a position and a limit - Parses streams of JSON values and JSON arrays from
java.io.InputStream/java.io.FileInputStreamwithout holding all input and parsed values in memory - Parses escaped characters in JSON keys and string values
- Derives codecs for primitives, boxed primitives, Java enums, Scala enumerations, Scala 3 enums, tuples,
String,BigInt,BigDecimal,Option,Either,java.util.UUID,java.time.*(ISO-8601 representation only), Scala collections, iterators, arrays (including immutable arrays in Scala 3), module classes, literal types, value classes, and case classes with fields of these types - Derives codecs for non-case Scala classes that have getters for all arguments of the primary constructor
- Supports primary constructors with multiple parameter lists and default values, including default values in non-first parameter lists that depend on preceding parameters (evaluated for missing fields after parsing all fields of a JSON object)
- Supports map keys of primitives, boxed primitives, enums,
String,BigInt,BigDecimal,java.util.UUID,java.time.*, literal types, and value classes of them - Supports first-order and higher-kinded types, and type aliases of all types above
- Supports 2 representations of ADTs with a sealed trait or a Scala class as a base type and non-abstract classes or objects as leaf classes: a discriminator field with a string value, or string values for objects and wrapper JSON objects for classes, with the discriminator value as the key
- Uses implicit value codecs and key codecs from the scope, so custom codecs can add types or change their JSON representation
- Uses implicit
Ordering[K]instances from the scope of themakecall for sorted maps and sets - Reads and writes byte arrays as Base16 and Base64 strings (RFC 4648) in custom codecs
- Reads and writes arbitrary bytes or raw values in custom codecs
- Treats fields with default values of the constructor as optional and other fields as required, with no annotations
- Skips serialization of fields with default values, or with empty options, collections, or arrays, for sparse output
- Skips parsing and serialization of fields that are annotated with
@transientor not defined in the constructor - Overrides field names with the
@namedannotation of constructor fields - Reads and writes numbers as strings for fields annotated with
@stringified - Preserves the order of instance fields when serializing with generated codecs, and parses objects with keys in that order faster
- Reports the hex offset of the error in parse exceptions for
Array[Byte],java.nio.ByteBuffer, andjava.io.InputStream/java.io.FileInputStreaminput, with an optional hex dump of the input around the error - Specializes key and value codecs for primitives, so they don't box or unbox values
- Parses from
java.io.InputStreamand serializes tojava.io.OutputStreamwithout extra buffering - Uses only black box macros, so codec derivation never changes your types
- Orders generated code to preserve checksums and maximize hit rates of remote build caches
- Prints generated codecs with an implicit
CodecMakerConfig.PrintCodecin the scope of codec derivation - Provides predefined derivation calls for common configurations:
makeWithoutDiscriminator,makeWithRequiredCollectionFields,makeWithRequiredCollectionFieldsAndNameAsDiscriminatorFieldName,makeWithRequiredDefaultFields,makeWithSkipNestedOptionValues,makeCirceLike,makeCirceLikeSnakeCased,makeOpenapiLike, andmakeOpenapiLikeWithoutDiscriminator - Suppresses all WartRemover warnings of generated codecs for Scala 2.12 and 2.13
- Implements
java.io.Serializablein codecs and runtime configurations for distributed computing - Supports simple opaque types like
opaque type Foo = Intandopaque type Bar <: String = String - Supports tuples with arities greater than 22 in Scala 3, backed by
scala.runtime.TupleXXL - Supports named tuples from Scala 3.7 while staying on Scala 3.3 (LTS)
- Supports shading to another package to lock a particular release
- Integrates with circe for faster parsing and serialization of circe AST, and for faster circe codecs
- Supports Scala 2.12, 2.13, and 3.3, JVMs of Java 11+, GraalVM native images, and Scala.js 1.0+ and Scala Native 0.5+ for all supported Scala versions
- Has no runtime dependencies except
scala-library(all platforms) andscala-java-time(a replacement ofjava.time._for Scala.js and Scala Native) - Keeps patch versions backward and forward compatible, and minor versions backward compatible
Limitations:
- Requires UTF-8 for byte input and output;
Stringinput and output works for other encodings but is much slower - Doesn't parse escaped characters of strings mapped to byte arrays, numbers, and
java.time.*types - Doesn't support cyclic graphs of class instances in generated codecs
- Rejects duplicated keys of class instances (except maps) with a parse exception
- Rejects
nullvalues withNullPointerExceptionwhen serializing - Rejects
nullvalues when parsing, except for optional or collection types (parsed asNoneor empty collections) and for fields with non-null default values - Requires correct
equalsimplementations for values used directly or in default values of constructor parameters (mostly non-case classes and types with custom codecs) - Requires a time zone database for time zones other than
UTCon Scala.js and Scala Native, see the scala-java-time documentation
Compile-time options of CodecMakerConfig:
- Reads and writes numbers as strings (
isStringified) - Reads numbers from both JSON numbers and JSON strings, while writing them as before (
allowStringifiedNumbers) - Reads integers from JSON numbers with fractions or exponents, like
1.0or1e0, when they are whole numbers (allowDecimalNotationForIntegers) - Reads and writes maps as JSON arrays (
mapAsArray) - Skips unexpected fields, or rejects them with a parse exception (
skipUnexpectedFields) - Turns off skipping serialization of fields with default values (
transientDefault), empty collections (transientEmpty), or empty options (transientNone) - Skips serialization of fields with
nullvalues for custom codecs of Scala 3 union types withNull(transientNull, Scala 3 only) - Requires collection fields (
requireCollectionFields) or fields with default values (requireDefaultFields) in JSON input - Uses default values of option and collection fields for missing fields only, instead of also for
nullvalues and empty collections (useDefaultForNullOrEmpty) - Rejects
nullvalues of collections with a parse exception instead of parsing them as empty collections (allowNullForCollections) - Maps names of fields (
fieldNameMapper), ADT leaf classes (adtLeafClassNameMapper), and Java enum values (javaEnumValueNameMapper) to JSON, with predefined mappers to snake_case, kebab-case, camelCase, or PascalCase - Sets an optional name of the discriminator field for ADTs (
discriminatorFieldName) - Serializes the discriminator field in codecs of ADT leaf classes too (
alwaysEmitDiscriminator) - Allows the discriminator field after other fields, which is a parse exception by default (
requireDiscriminatorFirst) - Encodes Scala objects of ADTs like circe does (
circeLikeObjectEncoding) - Parses and serializes Scala enumerations by ids (
useScalaEnumValueId) - Distinguishes
nulland missing fields asSome(None)andNonevalues ofOption[Option[_]](skipNestedOptionValues) - Parses both
nulland missing fields asNonevalues ofOption[Option[_]]when nested options are turned on (distinguishNullAndMissingNestedOptions) - Limits precision, scale, and digits of parsed
BigDecimalvalues (bigDecimalPrecision,bigDecimalScaleLimit,bigDecimalDigitsLimit: 34, 6178, and 308 by default) - Limits digits of parsed
BigIntvalues (bigIntDigitsLimit: 308 by default) - Limits values of parsed bit sets (
bitSetValueLimit: 1024 by default) - Limits inserts when parsing maps or sets (
mapMaxInsertNumber,setMaxInsertNumber: 1024 by default) - Allows recursive data structures, which are a compilation error by default (
allowRecursiveTypes) - Turns off derivation of codecs for nested classes, objects, ADTs, and enums, requiring implicit codecs like circe's
semi-automatic derivation, and custom key codecs for map keys of value classes (including inlined one-value classes)
and enums, or value codecs when
mapAsArrayis turned on, while options, tuples, Scala 3 named tuples and opaque types (but not their underlying types), recursive references to the derived type, and cases of derived ADTs are still derived (deriveNestedClasses). Unlike circe, value classes are serialized as their values, implicit codecs of ADT leaf classes are ignored when the discriminator field is used, andallowRecursiveTypesdoesn't check recursion across implicit codecs, so derive mutually recursive types in one codec to keep that check for untrusted input - Turns off checking of field duplication for smaller and faster codecs (
checkFieldDuplication) - Turns off generation of decoding or encoding for faster derivation and smaller class/JS/binary size (
encodingOnly,decodingOnly) - Inlines codecs of non-value classes that have a one-argument primary constructor (
inlineOneValueClasses) - Supports the
scala.transientannotation (scalaTransientSupport)
Runtime options of ReaderConfig and WriterConfig:
- Escapes non-ASCII chars for ASCII-only output (
escapeUnicode) - Indents output with the given number of spaces per level, or writes compact output by default (
indentionStep) - Turns on stack traces of exceptions for debugging, which are off by default for performance
(
throwReaderExceptionWithStackTrace,throwWriterExceptionWithStackTrace) - Turns off hex dumps in parse exceptions for performance (
appendHexDumpToParseException), or sets their size in 16-byte lines before and after the error line (hexDumpSize: 2 by default) - Turns off the check for non-whitespace bytes after the parsed value (
checkForEndOfInput) - Sets max and preferred sizes of input buffers for parsing from
java.io.InputStreamorjava.nio.DirectByteBuffer(maxBufSize,preferredBufSize: 32 MiB and 32 KiB by default) - Sets max and preferred sizes of char buffers for parsing strings, including Base16 and Base64 encoded ones
(
maxCharBufSize,preferredCharBufSize: 4M and 4K chars by default) - Sets the preferred size of output buffers for all outputs except byte arrays and heap byte buffers passed as
arguments (
preferredBufSize: 32 KiB by default)
Last releases for older platforms:
- v2.13.5.2: support of JDK 8, and native images of earlier GraalVM versions
- v2.13.3.2: support of Scala 2.11
- v2.30.2: support of Scala Native 0.4
For upcoming features and fixes see Commits and Issues page.
How to use
Let's assume that you have the following data structures:
case class Device(id: Int, model: String)
case class User(name: String, devices: Seq[Device])
Add the core library with a "compile" scope and the macros library with "compile-internal" or "provided" scopes to your list of sbt dependencies:
libraryDependencies ++= Seq(
// Use the %%% operator instead of %% for Scala.js and Scala Native
"com.github.plokhotnyuk.jsoniter-scala" %% "jsoniter-scala-core" % "2.45.0",
// Use the "provided" scope instead when the "compile-internal" scope is not supported
"com.github.plokhotnyuk.jsoniter-scala" %% "jsoniter-scala-macros" % "2.45.0" % "compile-internal"
)
At the start of a Scala CLI script, use the "dep" scope for the core library and the "compileOnly.dep" scope for the macros library:
//> using dep "com.github.plokhotnyuk.jsoniter-scala::jsoniter-scala-core::2.45.0"
//> using compileOnly.dep "com.github.plokhotnyuk.jsoniter-scala::jsoniter-scala-macros::2.45.0"
Derive a codec for the top-level type to parse or serialize:
import com.github.plokhotnyuk.jsoniter_scala.macros._
import com.github.plokhotnyuk.jsoniter_scala.core._
given userCodec: JsonValueCodec[User] = JsonCodecMaker.make
That's it! You have derived a com.github.plokhotnyuk.jsoniter_scala.core.JsonValueCodec for the whole nested data
structure. Nested classes like Device need their own codecs only to parse or serialize them separately from User,
or with a different derivation configuration.
Now use it for parsing and serialization from/to String:
val user = readFromString[User]("""{"name":"John","devices":[{"id":1,"model":"HTC One X"}]}""")
val json = writeToString(User("John", Seq(Device(2, "iPhone X"))))
For the network or disks, parse and serialize bytes, which is much more efficient:
- byte arrays using
readFromArray/writeToArray - byte sub-arrays using
readFromSubArray/writeToSubArray java.nio.ByteBufferinstances usingreadFromByteBuffer/writeToByteBufferjava.io.InputStream/java.io.OutputStreaminstances usingreadFromStream/writeToStream
Parsing from bytes also validates UTF-8 encoding and throws a parse exception for malformed bytes.
To print the generated code of codecs, add the following line to the scope of codec derivation before the make call:
given CodecMakerConfig.PrintCodec with {}
For more use cases, see the tests:
Specs of Scala 3 only features are in this directory.
NOTE: Until official docs will be published, please, use all these tests as tutorials and how-tos to help in your
journey to become happy users. Also, they are recommended to skim through for checking of your expectation before
selection of this library among others.
Online services that generate initial versions of your data structures from JSON samples:
Samples of integration with web frameworks and HTTP servers:
Usages of jsoniter-scala in OSS libraries:
- akka-http-json - integrates some of the best JSON libs in Scala with Akka HTTP
- bootzooka - a project to quickly start developing a Scala-based microservice or web app, without the need to write login, user registration etc.
- caliban - a purely functional library for building GraphQL servers and clients in Scala
- cats-eo - existential optics library for Scala3 based on cats
- dijon - support of schema-less JSON using safe and efficient AST representation
- geo-scala - a core AST and utilities for GeoJSON (RFC 7946) and more
- iron - a lightweight library for refined types in Scala 3
- kafka-serde-scala - implicitly converts typeclass encoders to kafka Serializer, Deserializer, Serde
- kindlings - hearth fire starter - incubator/dogfooding for Hearth-based macro libraries
- linkml-scala - a fast, portable (JS/JVM/native), and robust implementation of LinkML for cross-language data modeling
- logging4s - structured logging for Scala 3
- neotype - a friendly newtype library for Scala 3
- openapi-generator - a generator for Scala3 + sttp4 + jsoniter-scala
- oath - yet another scala-jwt library which has the aim to enhance user experience
- pekko-http-json - integrates some of the best JSON libs in Scala with Pekko HTTP
- play-json-jsoniter - provides the fastest way to convert an
instance of
play.api.libs.json.JsValueto byte array (or byte buffer, or output stream) and read it back - scalapb-jsoniter - JSON/Protobuf convertors for ScalaPB use jsoniter-scala
- scalatest-json - Scalatest matchers with appropriate equality and descriptive error messages
- smithy4s-json - JSON protocol of Smithy tooling for Scala
- sttp - the Scala HTTP client you always wanted!
- sttp-oauth2 - OAuth2 client library implemented in Scala using sttp
- tapir - typed API descRiptions
- zio-gcp - collection of generated Google Cloud clients for ZIO with authentication
- zio-schema-jsoniter - jsoniter-scala codecs for zio-schema
For usages in other OSS projects, see the Dependents section of the project's Scala Index page
To keep up with the latest releases, use the sbt-updates plugin or the Scala Steward service.
Known issues
- Parsing doesn't limit the total length of JSON input.
Workaround: check the length of untrusted input before readFromStream or other read... calls. Parse JSON arrays or
whitespace-separated JSON values with scanJsonArrayFromStream or scanJsonValuesFromStream instead of
readFromStream.
- Compilation of a
makecall fails when its configuration depends on code that uses the result of the macro call, because the configuration is evaluated at compile time:
[error] Cannot evaluate a parameter of the 'make' macro call for type 'full.name.of.YourType'. It should not depend on
code from the same compilation module where the 'make' macro is called. Use a separated submodule of the project
to compile all such dependencies before their usage for generation of codecs.
Workaround: compile such dependencies in a separate submodule. The Scala 2 compiler can fail with the same error even when the configuration has no clear dependencies on other code. Simpler workarounds for those cases:
- use
makeormake...macro calls without parameters - isolate the
makemacro call in a separate object, like in this PR - make jsoniter-scala imports local, like here and here
- use
sbt clean compile stageorsbt clean test stageinstead of justsbt clean stage, like in this repo - use
mill cleanif mill's native BSP support is used in IntelliJ IDEA - keep only one version of jsoniter-scala on the classpath: different versions (e.g. from transitive dependencies) cause
this error. Find them with
dependencyTree/dependencyGraphand remove them with exclusionRules
- Compilation fails with unexpected errors for ADT definitions or their derived codecs nested in classes or functions, like here.
Workaround: define ADTs and their codecs in an outer object, not in classes, traits, or functions.
- Compilation of
makecalls in Scala 3 fails for some expressions of name mappers in the configuration.
Workaround: use the supported expressions from examples of CodecMakerConfig usage in unit tests.
- Nested parsing or serialization routines fail with
unexpected errors, because they reuse the same
JsonReaderorJsonWriterinstance:
scanJsonValuesFromStream[String](in) { s =>
readFromString[String](s)
}
Workaround: use ...Reentrant routines for all but the innermost call. They create a new JsonReader or JsonWriter
instance on each call:
scanJsonValuesFromStreamReentrant[String](in) { s =>
readFromString[String](s)
}
- Scala.js doesn't support Java enums compiled from Java sources, so linking fails with errors like:
[error] Referring to non-existent class com.github.plokhotnyuk.jsoniter_scala.macros.Level
[error] called from private com.github.plokhotnyuk.jsoniter_scala.macros.JsonCodecMakerSpec.$anonfun$new$24()void
[error] called from private com.github.plokhotnyuk.jsoniter_scala.macros.JsonCodecMakerSpec.$anonfun$new$1()void
[error] called from constructor com.github.plokhotnyuk.jsoniter_scala.macros.JsonCodecMakerSpec.<init>()void
[error] called from static constructor com.github.plokhotnyuk.jsoniter_scala.macros.JsonCodecMakerSpec.<clinit>()void
[error] called from core module analyzer
Workaround for Scala 2: split sources for JVM and other platforms, and emulate Java enums for Scala.js and Scala Native.
Code for JVM:
public enum Level {
HIGH, LOW;
}
Code for Scala.js and Scala Native:
object Level {
val HIGH: Level = new Level("HIGH", 0)
val LOW: Level = new Level("LOW", 1)
val values: Array[Level] = Array(HIGH, LOW)
def valueOf(name: String): Level =
if (HIGH.name() == name) HIGH
else if (LOW.name() == name) LOW
else throw new IllegalArgumentException(s"Unrecognized Level name: $name")
}
final class Level private (name: String, ordinal: Int) extends Enum[Level](name, ordinal)
Workaround for Scala 3, the same for all platforms:
enum Level extends Enum[Level] {
case HIGH
case LOW
}
- The Scala 3 compiler fails to derive anonymous codecs for generic types with concrete type parameters:
case class DeResult[T](isSucceed: Boolean, data: T, message: String)
case class RootPathFiles(files: List[String])
given JsonValueCodec[DeResult[Option[String]]] = JsonCodecMaker.make
given JsonValueCodec[DeResult[RootPathFiles]] = JsonCodecMaker.make
Scala 3.2.x versions fail with a duplicate definition error like this:
[error] 19 | given JsonValueCodec[DeResult[RootPathFiles]] = JsonCodecMaker.make
[error] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[error] |given_JsonValueCodec_DeResult is already defined as given instance given_JsonValueCodec_DeResult
Workaround: name the codec instances:
given codecOfDeResult1: JsonValueCodec[DeResult[Option[String]]] = JsonCodecMaker.make
given codecOfDeResult2: JsonValueCodec[DeResult[RootPathFiles]] = JsonCodecMaker.make
or gather private type aliases with given definitions in a trait:
trait DeResultCodecs:
private type DeResult1 = DeResult[Option[String]]
private type DeResult2 = DeResult[RootPathFiles]
given JsonValueCodec[DeResult1] = JsonCodecMaker.make
given JsonValueCodec[DeResult2] = JsonCodecMaker.make
end DeResultCodecs
object DeResultCodecs extends DeResultCodecs
import DeResultCodecs.given
JsonCodecMaker.makecalls fail to derive codecs for Scala 3 union types or complex opaque types.
Workaround: define custom codecs for these types with implicit val before the JsonCodecMaker.make call, like here
and here.
- The default name mapper strips simple names of ADT leaf classes or objects up to the last dot, if they contain dots.
Workaround: use the @named annotation, like here:
sealed abstract class Version(val value: String)
object Version {
@named("8.10") case object `8.10` extends Version("8.10")
@named("8.09") case object `8.09` extends Version("8.9")
}
- Parsing of JSON strings to numbers or
java.time.*values fails for escaped ASCII characters.
Workaround: use custom codecs that parse those values as strings and then convert them, like here:
implicit val customCodecOfOffsetDateTime: JsonValueCodec[OffsetDateTime] = new JsonValueCodec[OffsetDateTime] {
private[this] val defaultCodec: JsonValueCodec[OffsetDateTime] = JsonCodecMaker.make[OffsetDateTime]
def nullValue: OffsetDateTime = null
def decodeValue(in: JsonReader, default: OffsetDateTime): OffsetDateTime = {
in.setMark()
try {
val x = in.readOffsetDateTime(default) // fast path for values without escaped characters
in.resetMark()
x
} catch {
case _: JsonReaderException =>
in.rollbackToMark()
val s = in.readString(null)
try readFromStringReentrant("\"" + s + "\"")(defaultCodec) catch {
case NonFatal(_) => in.decodeError("illegal offset date time")
}
}
}
def encodeValue(x: OffsetDateTime, out: JsonWriter): Unit = out.writeVal(x)
}
implicit defandinline givenmethods that generate custom codecs duplicate codec instances. Scala 3.5.0+ warns withNew anonymous class definition will be duplicated at each inline sitefor someinline givencases, and silently duplicates codec instances in other cases.
Workaround: convert methods of codec generation to def and derive custom codecs explicitly, like here:
object Tags {
opaque type Tagged[+V, +T] = Any
type @@[+V, +T] = V & Tagged[V, T]
def tag[T]: [V] => V => V @@ Tag = [V] => (v: V) => v
}
object Graph {
import Tags.{@@, tag}
def tagJsonValueCodec[V, T](codec: JsonValueCodec[V]): JsonValueCodec[V @@ T] = new JsonValueCodec[V @@ T]:
//println("+1")
override def decodeValue(in: JsonReader, default: V @@ T): V @@ T = tag[T](codec.decodeValue(in, default: V))
override def encodeValue(x: V @@ T, out: JsonWriter): Unit = codec.encodeValue(x, out)
override def nullValue: V @@ T = tag[T](codec.nullValue)
trait NodeIdTag
type NodeId = Int @@ NodeIdTag
case class Node(id: NodeId, name: String)
case class Edge(node1: NodeId, node2: NodeId)
given JsonValueCodec[Graph.NodeId] = Graph.tagJsonValueCodec(JsonCodecMaker.make)
given JsonValueCodec[Graph.Node] = JsonCodecMaker.make
given JsonValueCodec[Graph.Edge] = JsonCodecMaker.make
}
How to develop
Feel free to ask questions in chat, open issues, or contribute by creating pull requests (improvements to docs, code, and tests are highly appreciated).
The gh-pages branch has about 10Gb of historical benchmark results, so clone with the --single-branch option to
fetch sources only.
If developing on a fork, make sure to download the git tags (required by the sbt build):
git remote add upstream [email protected]:plokhotnyuk/jsoniter-scala.git
git fetch --tags upstream
Building of Scala.js and Scala Native modules requires Clang 18.x and Node.js 20.x. These commands work for me:
sudo apt install clang libstdc++-12-dev libgc-dev
curl https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash
source ~/.bashrc
nvm install 20
node -v
Get report of available dependency updates
sbt ";dependencyUpdates; reload plugins; dependencyUpdates; reload return"
Run tests, check coverage and binary compatibility
sbt -java-home /usr/lib/jvm/jdk-17 ++2.13.18 clean coverage jsoniter-scala-coreJVM/test jsoniter-scala-circeJVM/test jsoniter-scala-macrosJVM/test jsoniter-scala-benchmarkJVM/test coverageReport
sbt -java-home /usr/lib/jvm/jdk-17 clean +test +mimaReportBinaryIssues
BEWARE: jsoniter-scala is included in Scala Community Build for Scala 2 and Scala Open Community Build for Scala 3.
Run JVM benchmarks
Before running benchmarks, check that your CPU is in the performance mode, not powersave. On Linux, print the
current mode and set the performance mode with:
cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
for i in $(ls /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor); do echo performance | sudo tee $i; done
Then view your CPU frequency with:
cat /proc/cpuinfo | grep -i mhz
Stop unneeded applications and services. Print running services with:
sudo service --status-all | grep '\[ + \]'
sudo systemctl list-units --state running
Then clear the cache memory. On Linux, without a reboot:
sudo su
free -m -h && sync && echo 3 > /proc/sys/vm/drop_caches && free -m -h
Benchmarks use the sbt plugin for JMH. For their features and options, see Sbt-JMH docs and JMH tool docs
Learn how to write benchmarks in JMH samples and JMH articles posted in Aleksey Shipilёv’s and Nitsan Wakart’s blogs.
Print available options with:
sbt jsoniter-scala-benchmarkJVM/clean 'jsoniter-scala-benchmarkJVM/Jmh/run -h'
Benchmark results can be stored in different formats: *.csv, *.json, etc. List supported formats with:
sbt jsoniter-scala-benchmarkJVM/clean 'jsoniter-scala-benchmarkJVM/Jmh/run -lrf'
JMH runs benchmarks with different profilers. List supported profilers with (it can ask for the user password):
sbt jsoniter-scala-benchmarkJVM/clean 'jsoniter-scala-benchmarkJVM/Jmh/run -lprof'
Print help for profiler options with (replace <profiler_name> with a profiler from the command above):
sbt jsoniter-scala-benchmarkJVM/clean 'jsoniter-scala-benchmarkJVM/Jmh/run -prof <profiler_name>:help'
Set constant values of benchmark parameters with the -p option:
sbt jsoniter-scala-benchmarkJVM/clean 'jsoniter-scala-benchmarkJVM/Jmh/run -p size=1,10,100,1000 ArrayOf.*'
To see throughput with the allocation rate of generated codecs, run benchmarks with the GC profiler:
sbt jsoniter-scala-benchmarkJVM/clean 'jsoniter-scala-benchmarkJVM/Jmh/run -prof gc .*Reading.*'
Plot results stored in JSON with JMH Visualizer: drag and drop your file to the drop zone,
or pass an HTTP link to your file in the source parameter of the URL, like
here.
On Linux, see CPU event statistics normalized per operation with the perf profiler:
sbt jsoniter-scala-benchmarkJVM/clean 'jsoniter-scala-benchmarkJVM/Jmh/run -prof perfnorm TwitterAPIReading.jsoniterScala'
Run it with a list of events, e.g. to check CPU stalls with 16 threads:
sbt jsoniter-scala-benchmarkJVM/clean 'jsoniter-scala-benchmarkJVM/Jmh/run -t 16 -prof "perfnorm:event=cycles,instructions,uops_executed.core,uops_executed.stall_cycles,cache-references,cache-misses,cycle_activity.stalls_total,cycle_activity.stalls_mem_any,cycle_activity.stalls_l3_miss,cycle_activity.stalls_l2_miss,cycle_activity.stalls_l1d_miss" .*'
List available events of the perf profiler with:
perf list
To record benchmarks with the JFR profiler, use a command like this:
sbt jsoniter-scala-benchmarkJVM/clean 'jsoniter-scala-benchmarkJVM/Jmh/run -prof "jfr:dir=target/jfr-reports" -wi 10 -i 60 TwitterAPIReading.jsoniterScala'
Recordings are in the jsoniter-scala-benchmark/jvm/target/jfr-reports directory.
To record benchmarks with Async profiler, extract its binaries
to the /opt/async-profiler directory and set these runtime variables to capture kernel frames:
sudo sysctl kernel.perf_event_paranoid=1
sudo sysctl kernel.kptr_restrict=0
Then use a command like this:
sbt -java-home /usr/lib/jvm/jdk-21 jsoniter-scala-benchmarkJVM/clean 'jsoniter-scala-benchmarkJVM/Jmh/run -prof "async:dir=target/async-reports;interval=1000000;output=flamegraph;libPath=/opt/async-profiler/lib/libasyncProfiler.so" -jvmArgsAppend "-XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints" --p size=128 -wi 5 -i 10 jsoniterScala'
Direct and reverse flame graphs are in the jsoniter-scala-benchmark/jvm/target/async-reports directory.
BEWARE: -XX:+DebugNonSafepoints can corrupt reports due to a bug that is fixed only for JDK 21.
To list available events, start your app or benchmark, and run jps to print PIDs and names of running Java
processes. While your process is running, launch Async Profiler with the list option and its PID:
$ ~/Projects/com/github/jvm-profiling-tools/async-profiler/profiler.sh list 6924
Basic events:
cpu
alloc
lock
wall
itimer
Perf events:
page-faults
context-switches
cycles
instructions
cache-references
cache-misses
branches
branch-misses
bus-cycles
L1-dcache-load-misses
LLC-load-misses
dTLB-load-misses
mem:breakpoint
trace:tracepoint
Profile and print assembly code of the hottest methods with the following command. It requires
the hsdis library for the PrintAssembly feature:
sbt jsoniter-scala-benchmarkJVM/clean 'jsoniter-scala-benchmarkJVM/Jmh/run -prof perfasm -wi 10 -i 10 -p size=128 BigIntReading.jsoniterScala'
For more extras, options, and flame graphs, see Sbt-JMH docs.
Other benchmarks that compare jsoniter-scala with:
- kostya/benchmarks - JSON parsers for different programming languages and compilers
- simdjson-java#31 - the most performant Java parsers: simdjson-java, fastjson, jackson, etc.
- borer#30 - JSON parsers for Scala on samples from real APIs, mapped to simple types like strings and primitives only, with results for GraalVM EE Java 8 only
- scala-serialization#8 - the best binary parsers and serializers for Scala
- serialization-benchmark - binary and text serializers for Scala
- json-bench - JSON serializers for Scala on synthetic samples
- scala-json-parsers-performance - JSON parsers for Scala, parsing from and serializing to strings
- mison#1 - a state-of-the-art filter that by "building structural indices converts control flow into data flow, thereby largely eliminating inherently unpredictable branches in the program and exploiting the parallelism available in modern processors"
Run Scala.js benchmarks
Build the jsoniter-scala-benchmarkJS module with JS only packaging, using JDK 17+:
sbt -DassemblyJSBenchmarks -java-home /usr/lib/jvm/jdk-17 ++3.9.0 jsoniter-scala-benchmarkJS/fullOptJS
Then deploy it to GitHub pages, open it in a browser, and select the batch mode that stores results in a .zip file.
Merge unpacked results from browsers with: jq -s '[.[][]]' firefox/*.json >firefox.json
Use similar steps for WASM + JS (dependencies) packaging:
sbt -DassemblyWASMBenchmarks -java-home /usr/lib/jvm/jdk-17 ++3.9.0 jsoniter-scala-benchmarkJS/fullLinkJS
Then use WASM optimizer:
brew upgrade binaryen
wasm-opt --all-features --disable-custom-descriptors --disable-compact-imports -O3 main.wasm -o main-o3.wasm
Then deploy it to GitHub pages, open it in a browser, and select the batch mode that stores results in a .zip file.
Merge unpacked results from browsers with: jq -s '[.[][]]' firefox/*.json >firefox-wasm.json
Released versions of Scala.js benchmarks:
Run compilation time benchmarks
Use the circe-argonaut-compile-times project to compare compilation time of jsoniter-scala for deeply nested product types with other JSON parsers like argonaut, play-json, and circe in 3 modes: auto, semi-auto, and derivation.
For Scala 3 use the scala3-compile-tests project to compare compilation time of jsoniter-scala for Scala 3 enumerations (sum types) with circe in semi-auto mode.
Also see an amazing talk from Mateusz Kubuszok, co-author of Chimney, about approaches to type class derivation, and how a trick from jsoniter-scala greatly speeds up sane auto-derivation, which you can reuse for your type classes too.
Publish locally
Use publishing of SNAPSHOT versions to your local artifact repositories for testing with other libraries or applications.
Publish to the local Ivy repo:
sbt clean +publishLocal
Publish to the local Maven repo:
sbt clean +publishM2
Release
For version numbering use Recommended Versioning Scheme that is used in the Scala ecosystem.
Double-check binary and source compatibility, including behavior, and release using the following command on the environment with 16+GB of RAM:
sbt -java-home /usr/lib/jvm/jdk-17 -J-Xmx16g clean release
Do not push changes to GitHub until promoted artifacts for the new version are not available for downloading on Maven Central Repository to avoid binary compatibility check failures in triggered Travis CI builds.
The last step is updating of the tag info in a release list.
استكشف مشاريع مشابهة ومرتبطة
جارٍ التحميل…