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())
}
}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
@JsonIgnoreones) of these types:string,int,long,double,bool,T?,JsonValue,any, other such classes, andArray<T>andHashMap<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@JsonSnakeCaseon the class (customerName→customer_name). - Reading. A missing key leaves the field's default;
nullsets a nullable or object field to null and leaves others alone; a value of the wrong kind is aValueErrornaming the field's path.JsonMap.into(value, reflect(Order))reads a parsed value,JsonMap.update(obj, value)changes only the fields given, andJsonMap.intoList(array, reflect(Line))reads a list. - Writing.
JsonMap.write(obj)gives compact text,JsonMap.from(obj)aJsonValue. Every mapped field is written, null ones asnull. - 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 = -1nullable: bool = falsecls: ClassInfo = nullitem: JsonType = nullwritten: string = ""
class JsonField
Constructors
new JsonField(field: FieldInfo, key: string, type: JsonType)
Fields
field: FieldInfokey: stringtype: JsonType
class JsonPlan
Constructors
new JsonPlan(cls: ClassInfo)
Fields
cls: ClassInfofields: 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 ofcls.static fn update(obj: any, value: JsonValue) -> any— Setsobj's fields fromvalue(an object); fields with no key keep their values.static fn write(obj: any) -> string—objas compact JSON text.static fn from(obj: any) -> JsonValue—objas a JSON object.static fn intoList(value: JsonValue, cls: ClassInfo) -> Array<any>— Objects ofclsfrom a JSON array.static fn plan(cls: ClassInfo) -> JsonPlanstatic 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;owneris 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 typetas JSON.static fn anyJson(x: any) -> JsonValue— Any value as JSON, by what it holds.