1 using System;
2 using System.Json;
3
4 Result<UniquePtr<JsonArray>> MakePhilosophers()
5 {
6 JsonArray* philosophers = new JsonArray();
7 JsonObject* aristotle = new JsonObject();
8 auto result = aristotle->AddField("name", new JsonString(u"Aristotles"));
9 if (result.Error()) return Result<UniquePtr<JsonArray>>(ErrorId(result.GetErrorId()));
10 philosophers->AddItem(aristotle);
11
12 JsonObject* plato = new JsonObject();
13 result = plato->AddField("name", new JsonString(u"Plato"));
14 if (result.Error()) return Result<UniquePtr<JsonArray>>(ErrorId(result.GetErrorId()));
15 philosophers->AddItem(plato);
16
17 JsonObject* socrates = new JsonObject();
18 result = socrates->AddField("name", new JsonString(u"Socrates"));
19 if (result.Error()) return Result<UniquePtr<JsonArray>>(ErrorId(result.GetErrorId()));
20 philosophers->AddItem(socrates);
21 return Result<UniquePtr<JsonArray>>(UniquePtr<JsonArray>(philosophers));
22 }
23
24 int main()
25 {
26 Result<UniquePtr<JsonArray>> philosopherResult = MakePhilosophers();
27 if (philosopherResult.Error())
28 {
29 Console.Error() << philosopherResult.GetErrorMessage() << endl();
30 return 1;
31 }
32 JsonArray* philosophers = philosopherResult.Value().Get();
33 System.Text.CodeFormatter formatter(Console.Out());
34 auto result = philosophers->Write(formatter);
35 if (result.Error())
36 {
37 Console.Error() << result.GetErrorMessage() << endl();
38 return 1;
39 }
40 Result<string> toStringResult = philosophers->ToString();
41 if (toStringResult.Error())
42 {
43 Console.Error() << toStringResult.GetErrorMessage() << endl();
44 return 1;
45 }
46 string json = Rvalue(toStringResult.Value());
47 Console.Out() << json << endl();
48 Result<UniquePtr<JsonValue>> parseResult = ParseJson(json);
49 if (parseResult.Error())
50 {
51 Console.Error() << parseResult.GetErrorMessage() << endl();
52 return 1;
53 }
54 JsonValue* jsonValue = parseResult.Value().Get();
55 if (jsonValue is JsonArray*)
56 {
57 JsonArray* a = cast<JsonArray*>(jsonValue);
58 long n = a->Count();
59 for (long i = 0; i < n; ++i;)
60 {
61 JsonValue* item = a->GetItem(i);
62 if (item is JsonObject*)
63 {
64 JsonObject* o = cast<JsonObject*>(item);
65 Result<JsonValue*> vr = o->GetField("name");
66 if (vr.Error())
67 {
68 Console.Error() << vr.GetErrorMessage() << endl();
69 return 1;
70 }
71 JsonValue* v = vr.Value();
72 if (v != null)
73 {
74 if (v is JsonString*)
75 {
76 JsonString* s = cast<JsonString*>(v);
77 Console.Out() << s->Value() << endl();
78 }
79 else
80 {
81 Console.Error() << "JSON string expected" << endl();
82 return 1;
83 }
84 }
85 else
86 {
87 Console.Error() << "\'name\' field not found" << endl();
88 return 1;
89 }
90 }
91 }
92 }
93 else
94 {
95 Console.Error() << "JSON array expected" << endl();
96 return 1;
97 }
98 return 0;
99 }