29 #ifndef CPL_JSON_STREAMING_WRITER_H
30 #define CPL_JSON_STREAMING_WRITER_H
34 #if defined(__cplusplus) && !defined(CPL_SUPRESS_CPLUSPLUS)
41 class CPL_DLL CPLJSonStreamingWriter
44 typedef void (*SerializationFuncType)(
const char *pszTxt,
void *pUserData);
47 CPLJSonStreamingWriter(
const CPLJSonStreamingWriter &) =
delete;
48 CPLJSonStreamingWriter &operator=(
const CPLJSonStreamingWriter &) =
delete;
50 std::string m_osStr{};
51 SerializationFuncType m_pfnSerializationFunc =
nullptr;
52 void *m_pUserData =
nullptr;
53 bool m_bPretty =
true;
54 std::string m_osIndent = std::string(
" ");
55 std::string m_osIndentAcc{};
57 bool m_bNewLineEnabled =
true;
61 bool bFirstChild =
true;
62 explicit State(
bool bIsObjIn) : bIsObj(bIsObjIn)
66 std::vector<State> m_states{};
67 bool m_bWaitForValue =
false;
69 void Print(
const std::string &text);
72 static std::string FormatString(
const std::string &str);
73 void EmitCommaIfNeeded();
76 CPLJSonStreamingWriter(SerializationFuncType pfnSerializationFunc,
78 ~CPLJSonStreamingWriter();
80 void SetPrettyFormatting(
bool bPretty)
84 void SetIndentationSize(
int nSpaces);
87 const std::string &GetString()
const
92 void Add(
const std::string &str);
93 void Add(
const char *pszStr);
97 Add(
static_cast<std::int64_t
>(nVal));
99 void Add(
unsigned int nVal)
101 Add(
static_cast<std::int64_t
>(nVal));
103 void Add(std::int64_t nVal);
104 void Add(std::uint64_t nVal);
105 void Add(
float fVal,
int nPrecision = 9);
106 void Add(
double dfVal,
int nPrecision = 18);
111 void AddObjKey(
const std::string &key);
112 struct CPL_DLL ObjectContext
114 CPLJSonStreamingWriter &m_serializer;
116 ObjectContext(
const ObjectContext &) =
delete;
117 ObjectContext(ObjectContext &&) =
default;
119 explicit inline ObjectContext(CPLJSonStreamingWriter &serializer)
120 : m_serializer(serializer)
122 m_serializer.StartObj();
126 m_serializer.EndObj();
129 inline ObjectContext MakeObjectContext()
131 return ObjectContext(*
this);
136 struct CPL_DLL ArrayContext
138 CPLJSonStreamingWriter &m_serializer;
139 bool m_bForceSingleLine;
140 bool m_bNewLineEnabledBackup;
142 ArrayContext(
const ArrayContext &) =
delete;
143 ArrayContext(ArrayContext &&) =
default;
145 inline explicit ArrayContext(CPLJSonStreamingWriter &serializer,
146 bool bForceSingleLine =
false)
147 : m_serializer(serializer), m_bForceSingleLine(bForceSingleLine),
148 m_bNewLineEnabledBackup(serializer.GetNewLine())
150 if (m_bForceSingleLine)
151 serializer.SetNewline(
false);
152 m_serializer.StartArray();
156 m_serializer.EndArray();
157 if (m_bForceSingleLine)
158 m_serializer.SetNewline(m_bNewLineEnabledBackup);
161 inline ArrayContext MakeArrayContext(
bool bForceSingleLine =
false)
163 return ArrayContext(*
this, bForceSingleLine);
166 bool GetNewLine()
const
168 return m_bNewLineEnabled;
170 void SetNewline(
bool bEnabled)
172 m_bNewLineEnabled = bEnabled;
176 #endif // __cplusplus
180 #endif // CPL_JSON_STREAMING_WRITER_H