shithub: rjson

ref: c4ef9e2925f8baec22d6737872326736b31bf45f
dir: /test/t.c/

View raw version
#include <u.h>
#include <libc.h>
#include "json.h"
#include "../rjson.h"

typedef struct Sub Sub;
struct Sub {
	char *xyz;
};

RJSON_BEGIN(Sub_rjson)
	RJSON_STRING(Sub,xyz)
RJSON_END()

typedef struct Test Test;
struct Test {
	char *one;
	char *two;
	double num;
	int bool;
	Sub obj;
};

RJSON_BEGIN(Test_rjson)
	RJSON_STRING(Test,one)
	RJSON_STRING(Test,two)
	RJSON_NUMBER(Test,num)
	RJSON_BOOL(Test,bool)
	RJSON_OBJECT(Test,obj,Sub_rjson)
RJSON_END()


char *testjson = ""
"{\n"
"	\"one\": \"eins\",\n"
"	\"two\": \"zwei\",\n"
"	\"num\": 5.540000,\n"
"	\"bool\": true,\n"
"	\"obj\": {\n"
"		\"xyz\": \"abc\"\n"
"	}\n"
"}\n";

void
main()
{
	Test t;
	JSON *j;
	char *s;
	int verbose;
	verbose = !!getenv("verbose");
	
	JSONfmtinstall();
	
	j = jsonparse(testjson);
	if (!j)
		sysfatal("%r");
	
	if (verbose) fprint(2, "=== Testing rjsontostruct\n");
	if (rjsontostruct(j, Test_rjson, &t)) {
		if (verbose) {
			fprint(2, "parsed: %r\n");
			fprint(2, "  one: %s\n", t.one);
			fprint(2, "  two: %s\n", t.two);
			fprint(2, "  num: %f\n", t.num);
			fprint(2, " bool: %d\n", t.bool);
			fprint(2, "     obj.xyz: %s\n", t.obj.xyz);
		}
	} else {
		fprint(2, "parse failed: %r\n");
	}
	
	jsonfree(j);
	
	if (verbose) fprint(2, "=== Testing rstructtojson\n");
	j = rstructtojson(&t, Test_rjson);
	if (!j)
		sysfatal("err: %r");
	if (verbose)
		fprint(2, "%J\n", j);
	
	s = smprint("%J\n", j);
	
	if (strcmp(s, testjson) != 0)
		exits("test failed");
	
	exits(nil);
}