aboutsummaryrefslogtreecommitdiff
path: root/README.md
blob: 2be2cfefbfe8f1be569f7d77eb2fdc710c93520c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# Install instructions
Coming later
# API
## Creating json
### Basic getting and setting
- To access a child of a json object use the array operators, e.g. `jsonObject["childName"]`
- To set a leaf child to be an instance of a class use the set method, e.g. `leaf.set<int>(2)`
- To read a leaf child's value use the get method, this will return a reference, e.g. `leaf.get<int>()` (note: this will cast the data stored in the leaf to whatever type you specify, so if the type you're trying to read is different to what was set then unintended consequences can occur)
- To set a list supply the set function with a vector and use the type of the elements in the array, e.g. `leaf.set<int>({1, 2, 3})`
### Adding new types
If you want to set a leaf to be a variable of a type that has not yet been added to the base library, then you must define a serializer for it.

This can be done by defining the templated function `TehJSON::JSON::serializeData<T>(T*)`. Example below:
```c++
template <> std::string TehJSON::JSON::serializeData<bool>(bool *data)
{
	return (*data)?"true":"false";
}
```
### Example
```c++
TehJSON::JSON jsonWriter;

jsonWriter["test_string"].set<std::string>("stringy");
jsonWriter["test_int"].set<int>(123);
jsonWriter["test_float"].set<float>(51.8);
jsonWriter["test_vecs"]["int"].set<int>({1, 2, 3});
jsonWriter["test_vecs"]["float"].set<float>({0.1, 0.2, 0.3});
jsonWriter["test_true"].set(true);
jsonWriter["test_false"].set(false);
jsonWriter["test_object"]["test_int"].set<int>(100);
jsonWriter["test_object"]["test_float"].set<float>(100);

jsonWriter["test_float"].get<float>() += 15;
jsonWriter["test_object"]["test_int"].get<int>() += 10;

std::string jsonString = jsonWriter.getSerialized();
```
Output:
```json
{
	"test_false": false,
	"test_float": 66.800003,
	"test_int": 123,
	"test_object": {
		"test_float": 100.000000,
		"test_int": 110
	},
	"test_string": "stringy",
	"test_true": true,
	"test_vecs": {
		"float": [0.100000, 0.200000, 0.300000],
		"int": [1, 2, 3]
	}
}
```
Note that the output will always list children in alphabetical order.
## Reading json
Use the function `TehJSON::JSON::readFromString`. This will ignore all whitespace (spaces, tabs, and newlines) so no need to make sure json is formatted nicely.
```c++
TehJSON::JSON jsonReader;
jsonReader.readFromString(jsonString);
```
Currently the only literals supported for reading are int, string, and float. Arrays can only be made up of these literals, and must be all of the same type.

If the tokenizer or json reading encounters an error they will throw an exception.