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;
62 bool bFirstChild =
true;
64 explicit State(
bool bIsObjIn) : bIsObj(bIsObjIn)
69 std::vector<State> m_states{};
70 bool m_bWaitForValue =
false;
72 void Print(
const std::string &text);
75 static std::string FormatString(
const std::string &str);
76 void EmitCommaIfNeeded();
79 CPLJSonStreamingWriter(SerializationFuncType pfnSerializationFunc,
81 ~CPLJSonStreamingWriter();
83 void SetPrettyFormatting(
bool bPretty)
88 void SetIndentationSize(
int nSpaces);
91 const std::string &GetString()
const
96 void Add(
const std::string &str);
97 void Add(
const char *pszStr);
102 Add(
static_cast<std::int64_t
>(nVal));
105 void Add(
unsigned int nVal)
107 Add(
static_cast<std::int64_t
>(nVal));
110 void Add(std::int64_t nVal);
111 void Add(std::uint64_t nVal);
112 void Add(
float fVal,
int nPrecision = 9);
113 void Add(
double dfVal,
int nPrecision = 18);
118 void AddObjKey(
const std::string &key);
120 struct CPL_DLL ObjectContext
122 CPLJSonStreamingWriter &m_serializer;
124 ObjectContext(
const ObjectContext &) =
delete;
125 ObjectContext(ObjectContext &&) =
default;
127 explicit inline ObjectContext(CPLJSonStreamingWriter &serializer)
128 : m_serializer(serializer)
130 m_serializer.StartObj();
135 m_serializer.EndObj();
139 inline ObjectContext MakeObjectContext()
141 return ObjectContext(*
this);
147 struct CPL_DLL ArrayContext
149 CPLJSonStreamingWriter &m_serializer;
150 bool m_bForceSingleLine;
151 bool m_bNewLineEnabledBackup;
153 ArrayContext(
const ArrayContext &) =
delete;
154 ArrayContext(ArrayContext &&) =
default;
156 inline explicit ArrayContext(CPLJSonStreamingWriter &serializer,
157 bool bForceSingleLine =
false)
158 : m_serializer(serializer), m_bForceSingleLine(bForceSingleLine),
159 m_bNewLineEnabledBackup(serializer.GetNewLine())
161 if (m_bForceSingleLine)
162 serializer.SetNewline(
false);
163 m_serializer.StartArray();
168 m_serializer.EndArray();
169 if (m_bForceSingleLine)
170 m_serializer.SetNewline(m_bNewLineEnabledBackup);
174 inline ArrayContext MakeArrayContext(
bool bForceSingleLine =
false)
176 return ArrayContext(*
this, bForceSingleLine);
179 bool GetNewLine()
const
181 return m_bNewLineEnabled;
184 void SetNewline(
bool bEnabled)
186 m_bNewLineEnabled = bEnabled;
Core portability definitions for CPL.