simdjson-kotlin v0.1.0

Guides

On-Demand API

The On-Demand API decodes values lazily as you touch them. Nothing builds a full tree, so it’s faster and allocates far less than the DOM, at the cost of forward-only access.

Iterating

iterate returns a JsonDocument. Walk it in document order:

kotlin
val json: ByteArray = loadTwitterJson()

SimdJsonParser().use { parser ->
    parser.iterate(json).use { doc ->
        for (tweet in doc.getObject()["statuses"].getArray()) {
            val user = tweet.getObject()["user"].getObject()
            if (user["default_profile"].getBoolean()) {
                println(user["screen_name"].getString())
            }
        }
    }
}

Reading values

Navigate with getObject() / getArray(), then pull scalars with the typed getters:

ParameterDescription
JsonDocumentAutoCloseableRoot value: getObject(), getArray(), getString(), getLong(), getULong(), getDouble(), getBoolean(), isNull(), getType().
OnDemandObjectIterable<OnDemandField>Forward-only object. obj["field"] and obj.findField("field") both return an OnDemandValue.
OnDemandArrayIterable<OnDemandValue>Forward-only array. Iterate to read its elements.
OnDemandValueAutoCloseableA not-yet-decoded value: the same typed getters as JsonDocument, plus materialize().
OnDemandFieldA single object entry: name and value.

Need a random-access snapshot of a subtree? OnDemandValue.materialize() decodes it into a DOM JsonValue:

kotlin
val user: JsonValue = tweet.getObject()["user"].materialize()

Forward-only rules

On-Demand trades random access for speed. Three rules follow from that:

Lifecycle

The JsonDocument, and every value it yields, live on the parser’s buffers, so close the document when you’re done. iterate(json).use { doc -> … } does that, and closing the parser closes everything under it. Both are AutoCloseable.

DOM or On-Demand?

Reach for…When
On-DemandYou read each field once, in order, and want the lowest latency and allocation.
DOMYou need random access, multiple passes, or want to keep values after the parser closes.
SerializationYou’re on the JVM and want to decode straight into @Serializable classes.