Grav v1.14.0

JSON into objects

import "std/data" (included in import "std") · namespace std.data

JsonMap reads JSON straight into your classes and writes them back, by reflection: no hand-written getString/set calls per field.

grav
import "std"

class Line {
    public sku: string = ""
    public qty: int = 0
    constructor() {}
}

@JsonSnakeCase class Order {
    public id: long = 0
    public customerName: string = ""
    @JsonName("total_cents") public total: long = 0
    public note: string? = null
    public lines: Array<Line> = new Array<Line>()
    public meta: HashMap<string, string> = new HashMap<string, string>()
    @JsonIgnore public cached: string = ""
    constructor() {}
}

fn main() {
    let order = JsonMap.read::<Order>("{\"id\": 7, \"customer_name\": \"Ada\", \"total_cents\": 1250, " +
                                     "\"lines\": [{\"sku\": \"A1\", \"qty\": 2}], \"meta\": {\"source\": \"web\"}}")
    print("${order.customerName} owes ${order.total} for ${order.lines[0].qty} x ${order.lines[0].sku}")
    order.note = "gift"
    print(JsonMap.write(order))
    try {
        JsonMap.read::<Order>("{\"lines\": [{\"qty\": \"two\"}]}")
    } catch (e: ValueError) {
        print(e.message())
    }
}
Output
Ada owes 1250 for 2 x A1
{"id":7,"customer_name":"Ada","total_cents":1250,"note":"gift","lines":[{"sku":"A1","qty":2}],"meta":{"source":"web"}}
JSON field 'lines[0].qty' must be a whole number, not "two"
  • What is mapped. A class's public fields (not private ones, not @JsonIgnore ones) of these types: string, int, long, double, bool, T?, JsonValue, any, other such classes, and Array<T> and HashMap<string, T> of any of these. The class needs a constructor without arguments.
  • Keys. A field's name, @JsonName("key") on a field, or every field in snake case with @JsonSnakeCase on the class (customerName → customer_name).
  • Reading. A missing key leaves the field's default; null sets a nullable or object field to null and leaves others alone; a value of the wrong kind is a ValueError naming the field's path. JsonMap.into(value, reflect(Order)) reads a parsed value, JsonMap.update(obj, value) changes only the fields given, and JsonMap.intoList(array, reflect(Line)) reads a list.
  • Writing. JsonMap.write(obj) gives compact text, JsonMap.from(obj) a JsonValue. Every mapped field is written, null ones as null.
  • Cost. Each class's mapping is worked out once and kept. Reading a 9-field object takes about 4.3 µs (parsing included) against 2.6 µs by hand, and writing about 4 µs.

API

class JsonType

How one type is read and written. kind: 0 string, 1 int, 2 long, 3 float (double), 4 bool, 5 JsonValue, 6 any, 7 an object of cls, 8 Array<item>, 9 HashMap<string, item>; -1 not mapped.

Constructors

  • new JsonType()

Fields

  • kind: int = -1
  • nullable: bool = false
  • cls: ClassInfo = null
  • item: JsonType = null
  • written: string = ""

class JsonField

Constructors

  • new JsonField(field: FieldInfo, key: string, type: JsonType)

Fields

  • field: FieldInfo
  • key: string
  • type: JsonType

class JsonPlan

Constructors

  • new JsonPlan(cls: ClassInfo)

Fields

  • cls: ClassInfo
  • fields: Array<JsonField> = new Array<JsonField>()

class JsonMap

Static members

  • static fn read<T>(text: string) -> T — JSON text as a new T (ValueError when it is not valid, or does not fit).
  • static fn into(value: JsonValue, cls: ClassInfo) -> any — A parsed value as a new object of cls.
  • static fn update(obj: any, value: JsonValue) -> any — Sets obj's fields from value (an object); fields with no key keep their values.
  • static fn write(obj: any) -> string — obj as compact JSON text.
  • static fn from(obj: any) -> JsonValue — obj as a JSON object.
  • static fn intoList(value: JsonValue, cls: ClassInfo) -> Array<any> — Objects of cls from a JSON array.
  • static fn plan(cls: ClassInfo) -> JsonPlan
  • static fn snake(name: string) -> string — "customerName" -> "customer_name"
  • static fn typeOf(written: string, owner: string) -> JsonType — A type as written ("Array<User>", "int?") -> how to map it; owner is the declaring class, whose namespace qualifies a bare class name.
  • static fn natural(v: JsonValue) -> any — A JSON value as plain Grav values: null, bool, long, double, string, Array<any>, HashMap<string, any>.
  • static fn json(x: any, t: JsonType) -> JsonValue — A value of type t as JSON.
  • static fn anyJson(x: any) -> JsonValue — Any value as JSON, by what it holds.

Edit this page on GitHub