1//
2// ParseHandler.cpp
3//
4// Library: JSON
5// Package: JSON
6// Module: ParseHandler
7//
8// Copyright (c) 2012, Applied Informatics Software Engineering GmbH.
9// and Contributors.
10//
11// SPDX-License-Identifier: BSL-1.0
12//
13
14
15#include "Poco/JSON/ParseHandler.h"
16#include "Poco/JSON/Object.h"
17#include "Poco/JSON/JSONException.h"
18
19
20using Poco::Dynamic::Var;
21
22
23namespace Poco {
24namespace JSON {
25
26
27ParseHandler::ParseHandler(bool preserveObjectOrder) : Handler(),
28 _preserveObjectOrder(preserveObjectOrder)
29{
30}
31
32
33ParseHandler::~ParseHandler()
34{
35}
36
37
38void ParseHandler::reset()
39{
40 while (!_stack.empty()) _stack.pop();
41 _key = "";
42 _result.empty();
43}
44
45
46void ParseHandler::startObject()
47{
48 Object::Ptr newObj = new Object(_preserveObjectOrder);
49 if (_stack.empty()) // The first object
50 {
51 _result = newObj;
52 }
53 else
54 {
55 Var parent = _stack.top();
56
57 if (parent.type() == typeid(Array::Ptr))
58 {
59 Array::Ptr arr = parent.extract<Array::Ptr>();
60 arr->add(newObj);
61 }
62 else if (parent.type() == typeid(Object::Ptr))
63 {
64 poco_assert_dbg(!_key.empty());
65 Object::Ptr obj = parent.extract<Object::Ptr>();
66 obj->set(_key, newObj);
67 _key.clear();
68 }
69 }
70
71 _stack.push(newObj);
72}
73
74
75void ParseHandler::endObject()
76{
77 if (!_stack.empty()) _stack.pop();
78}
79
80
81void ParseHandler::startArray()
82{
83 Array::Ptr newArr = new Array();
84
85 if (_stack.empty()) // The first array
86 {
87 _result = newArr;
88 }
89 else
90 {
91 Var parent = _stack.top();
92
93 if (parent.type() == typeid(Array::Ptr))
94 {
95 Array::Ptr arr = parent.extract<Array::Ptr>();
96 arr->add(newArr);
97 }
98 else if (parent.type() == typeid(Object::Ptr))
99 {
100 poco_assert_dbg(!_key.empty());
101 Object::Ptr obj = parent.extract<Object::Ptr>();
102 obj->set(_key, newArr);
103 _key.clear();
104 }
105 }
106
107 _stack.push(newArr);
108}
109
110
111void ParseHandler::endArray()
112{
113 if (!_stack.empty()) _stack.pop();
114}
115
116
117void ParseHandler::key(const std::string& k)
118{
119 _key = k;
120}
121
122
123void ParseHandler::setValue(const Var& value)
124{
125 if (_stack.size())
126 {
127 Var parent = _stack.top();
128
129 if (parent.type() == typeid(Array::Ptr))
130 {
131 Array::Ptr arr = parent.extract<Array::Ptr>();
132 arr->add(value);
133 }
134 else if (parent.type() == typeid(Object::Ptr))
135 {
136 Object::Ptr obj = parent.extract<Object::Ptr>();
137 obj->set(_key, value);
138 _key.clear();
139 }
140 }
141 else
142 {
143 throw JSONException("Attempt to set value on an empty stack");
144 }
145}
146
147
148} } // namespace Poco::JSON
149