Skip to content

Commit 2db627e

Browse files
author
Daniel Lemire
committed
adding missing file
1 parent eba7364 commit 2db627e

1 file changed

Lines changed: 67 additions & 0 deletions

File tree

examples/demo.cpp

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
#include "simdjson.h"
2+
#include "simdjson/json_builder/json_builder.h"
3+
#include <format>
4+
5+
struct kid {
6+
int age;
7+
std::string name;
8+
std::vector<std::string> toys;
9+
};
10+
11+
namespace simdjson {
12+
// Helper code because simdjson does not use reflect for now
13+
template <typename T>
14+
requires(simdjson::json_builder::UserDefinedType<T>)
15+
simdjson_result<T> tag_invoke(deserialize_tag, std::type_identity<T>,
16+
auto &val) {
17+
ondemand::object obj;
18+
auto error = val.get_object().get(obj);
19+
if (error) {
20+
return error;
21+
}
22+
T t;
23+
for (auto keyval : obj) {
24+
std::string_view key;
25+
SIMDJSON_TRY(keyval.escaped_key().get(key));
26+
[:json_builder::expand(std::meta::nonstatic_data_members_of(^T)
27+
):] >> [&]<auto mem> {
28+
if (key == std::string_view(std::meta::identifier_of(mem))) {
29+
error = keyval.value().get(t.[:mem:]);
30+
}
31+
};
32+
if (error) {
33+
return error;
34+
}
35+
}
36+
return t;
37+
}
38+
39+
} // namespace simdjson
40+
41+
/**
42+
43+
I am 12 years old
44+
I have a car
45+
I have a ball
46+
My name is John
47+
My JSON is {"age":12,"name":"John","toys":["car","ball"]}
48+
49+
*/
50+
void demo() {
51+
simdjson::padded_string json_str =
52+
R"({"age": 12, "name": "John", "toys": ["car", "ball"]})"_padded;
53+
simdjson::ondemand::parser parser;
54+
auto doc = parser.iterate(json_str);
55+
kid k = doc.get<kid>();
56+
std::print("I am {} years old\n", k.age);
57+
for (const auto &toy : k.toys) {
58+
std::print("I have a {}\n", toy);
59+
}
60+
std::print("My name is {}\n", k.name);
61+
62+
std::print("My JSON is {}\n", simdjson::json_builder::to_json_string(k));
63+
}
64+
int main() {
65+
demo();
66+
return EXIT_SUCCESS;
67+
}

0 commit comments

Comments
 (0)