added example for null value to marshaller demo

This commit is contained in:
overflowerror 2021-05-03 21:06:58 +02:00
parent ac78c7856c
commit 091132e27c
5 changed files with 71 additions and 3 deletions

View file

@ -37,6 +37,15 @@ obj/%.o: src/%.c obj
obj:
@mkdir -p obj
marshaller-demo: marshaller/gen/demo.tab.c marshaller/demo/demo.c marshaller/marshaller.c $(A_LIB_NAME)
$(CC) $(CFLAGS) -Imarshaller/demo/ -Isrc/ -Imarshaller/ -o $@ $^
marshaller/gen/demo.tab.c: marshaller/demo/demo.h marshaller/marshaller-gen
./marshaller/marshaller-gen -o $@ $<
marshaller/marshaller-gen:
$(MAKE) -C marshaller/ marshaller-gen
clean:
@echo "Cleaning up..."
@rm -f obj/*.o
@ -45,3 +54,4 @@ clean:
@rm -f $(BIN_NAME)
@rm -f $(A_LIB_NAME)
@rm -f $(SO_LIB_NAME)
$(MAKE) -C marshaller/ clean

View file

@ -3,9 +3,9 @@ YACC = bison
YFLAGS = -y -d
CC = gcc
BIN_NAME = marshaller
BIN_NAME = marshaller-gen
marshaller: src/codegen.c gen/lex.yy.c gen/y.tab.c
$(BIN_NAME): src/codegen.c gen/lex.yy.c gen/y.tab.c
$(CC) -Isrc/ -o $@ $^
gen/y.tab.c gen/y.tab.h: src/parser.y
@ -19,4 +19,3 @@ gen/lex.yy.c: src/scanner.l gen/y.tab.h
clean:
rm -f gen/* $(BIN_NAME)

40
marshaller/demo/demo.c Normal file
View file

@ -0,0 +1,40 @@
#include <stdio.h>
#include <stdlib.h>
#include <json.h>
#include <marshaller.h>
#include "demo.h"
int main() {
const char* json = "{\
\"name\": \"How To Write A JSON Marshaller In C\",\
\"content\": \"TODO\",\
\"views\": null,\
\"user\": {\
\"uid\": 1000,\
\"username\": \"overflowerror\",\
\"email\": \"overflow@persei.net\"\
}\
}";
post_t* post = json_unmarshall(post_t, json);
printf("Name: %s\n", post->name);
printf("Content: %s\n", post->content);
printf("Views: %s (%ld)\n", post->views == NULL ? "null" : "", post->views == NULL ? 0 : *post->views);
printf("User.Uid: %lld\n", post->user.uid);
printf("User.Username: %s\n", post->user.username);
printf("User.Email: %s\n", post->user.email);
printf("\n");
post->content = "Just do it.";
char* newJson = json_marshall(post_t, post);
printf("%s\n", newJson);
free(newJson);
return 0;
}

18
marshaller/demo/demo.h Normal file
View file

@ -0,0 +1,18 @@
#ifndef DEMO_H
#define DEMO_H
typedef struct {
long long uid;
const char* username;
const char* email;
} user_t;
typedef struct {
const char* name;
const char* content;
long* views;
user_t user;
} post_t;
#endif

View file

@ -1,6 +1,7 @@
#ifndef JSON_H
#define JSON_H
#include <stdlib.h>
#include <stdbool.h>
typedef enum {