Creating JSON
It's also easy to create a typed JSON structure using Ribs using the Json
class:
final anObject = Json.obj([
('key1', Json.True),
('key2', Json.str('some string...')),
(
'key3',
Json.arr([
Json.number(123),
Json.number(3.14),
])
),
]);
By passing a list of (String, Json) elements to the Json.obj function, we now have a fully
typed Json object that we can interact with using the Ribs json API.
info
In many cases, you probably won't need to use the Json API itself. It's far
more common to define your domain models, and create encoders and decoders
for those. But it's still worthwhile knowing the Json type is what makes the
higher level APIs work.
What about serializing the JSON? That's also an easy task:
final jsonString = anObject.printWith(Printer.noSpaces);
// {"key1":true,"key2":"some string...","key3":[123,3.14]}
final prettyJsonString = anObject.printWith(Printer.spaces2);
// {
// "key1" : true,
// "key2" : "some string...",
// "key3" : [
// 123,
// 3.14
// ]
// }