Haxe Typed Json Parser
Runtime Typed Json implementation.
Install
haxelib install typed-json
Usage
Sample
typedef SomeStruct = {bla:String}
//Create a Parser, that parses into a specific type
var myParser = new hx.json.TypedJson<SomeStruct>();
//Parsing a file
switch(myParser.parse(hx.streams.FileInput(filename))){
case ResultData(parsedData):
//Process the parsed data
trace(parsedData); //is of type SomeStruct
case WithParsingError(parsingError): // Invalid JSON
//Process the Error
hx.json.parser.ErrorDetail.ErrorDetailFollower.trace(error);
case WithDataError(dataError): // JSON does not match expected Datatype
//Process the Error
trace(dataError); //is of type String
}
Creating the Parser
//define some types
typedef SomeStruct = {
hallo:String
};
typedef SomeOtherStruct = {
> SomeStruct, // the other fields will be set as well
?bla:Bool, // if not in JSON, null will be used
hi:Array<Bool>,
map: Map<String, Float>
};
var myParser1 = new hx.json.TypedJson<{foo:String,?bla:Bool}>();
var myParser2 = new hx.json.TypedJson<SomeStruct>();
var myParser3 = new hx.json.TypedJson<SomeOtherStruct>();
var myParser4 = new hx.json.TypedJson<Int>();
var myParser4 = new hx.json.TypedJson<Map<String, Float>>();
Errormessages
Parsing Errors
case WithParsingError(parsingError): hx.json.parser.ErrorDetail.ErrorDetailFollower.trace(error);
Sample Errormessage:
###############
ERROR in "samplefile.json" @1,9: Expected ":", found "1"!
1 | {"hallo"1:"hi"}
----- + ^
###############
Data Errors
case WithDataError(dataError): trace(dataError);
Sample Errormessage:
"$.hallo" should be StringValue, but was BooleanValue
Json was {"hallo":true} and {hallo:String} was the required type.