13#ifndef CPL_JSON_STREAMING_WRITER_H
14#define CPL_JSON_STREAMING_WRITER_H
18#if defined(__cplusplus) && !defined(CPL_SUPRESS_CPLUSPLUS)
25class CPL_DLL CPLJSonStreamingWriter
28 typedef void (*SerializationFuncType)(
const char *pszTxt,
void *pUserData);
31 CPLJSonStreamingWriter(
const CPLJSonStreamingWriter &) =
delete;
32 CPLJSonStreamingWriter &operator=(
const CPLJSonStreamingWriter &) =
delete;
34 std::string m_osStr{};
35 SerializationFuncType m_pfnSerializationFunc =
nullptr;
36 void *m_pUserData =
nullptr;
37 bool m_bPretty =
true;
38 std::string m_osIndent = std::string(
" ");
39 std::string m_osIndentAcc{};
41 bool m_bNewLineEnabled =
true;
46 bool bFirstChild =
true;
48 explicit State(
bool bIsObjIn) : bIsObj(bIsObjIn)
53 std::vector<State> m_states{};
54 bool m_bWaitForValue =
false;
56 void Print(
const std::string &text);
59 static std::string FormatString(
const std::string &str);
60 void EmitCommaIfNeeded();
63 CPLJSonStreamingWriter(SerializationFuncType pfnSerializationFunc,
65 ~CPLJSonStreamingWriter();
67 void SetPrettyFormatting(
bool bPretty)
72 void SetIndentationSize(
int nSpaces);
75 const std::string &GetString()
const
80 void Add(
const std::string &str);
81 void Add(
const char *pszStr);
86 Add(
static_cast<std::int64_t
>(nVal));
89 void Add(
unsigned int nVal)
91 Add(
static_cast<std::int64_t
>(nVal));
94 void Add(std::int64_t nVal);
95 void Add(std::uint64_t nVal);
96 void Add(
float fVal,
int nPrecision = 9);
97 void Add(
double dfVal,
int nPrecision = 18);
102 void AddObjKey(
const std::string &key);
104 struct CPL_DLL ObjectContext
106 CPLJSonStreamingWriter &m_serializer;
108 ObjectContext(
const ObjectContext &) =
delete;
109 ObjectContext(ObjectContext &&) =
default;
111 explicit inline ObjectContext(CPLJSonStreamingWriter &serializer)
112 : m_serializer(serializer)
114 m_serializer.StartObj();
119 m_serializer.EndObj();
123 inline ObjectContext MakeObjectContext()
125 return ObjectContext(*
this);
131 struct CPL_DLL ArrayContext
133 CPLJSonStreamingWriter &m_serializer;
134 bool m_bForceSingleLine;
135 bool m_bNewLineEnabledBackup;
137 ArrayContext(
const ArrayContext &) =
delete;
138 ArrayContext(ArrayContext &&) =
default;
140 inline explicit ArrayContext(CPLJSonStreamingWriter &serializer,
141 bool bForceSingleLine =
false)
142 : m_serializer(serializer), m_bForceSingleLine(bForceSingleLine),
143 m_bNewLineEnabledBackup(serializer.GetNewLine())
145 if (m_bForceSingleLine)
146 serializer.SetNewline(
false);
147 m_serializer.StartArray();
152 m_serializer.EndArray();
153 if (m_bForceSingleLine)
154 m_serializer.SetNewline(m_bNewLineEnabledBackup);
158 inline ArrayContext MakeArrayContext(
bool bForceSingleLine =
false)
160 return ArrayContext(*
this, bForceSingleLine);
163 bool GetNewLine()
const
165 return m_bNewLineEnabled;
168 void SetNewline(
bool bEnabled)
170 m_bNewLineEnabled = bEnabled;
Core portability definitions for CPL.