ppsspp/ext/native/json/json_writer.h

92 lines
2.3 KiB
C
Raw Normal View History

2012-03-31 11:16:13 +02:00
// Minimal-state JSON writer. Consumes almost no memory
2012-03-24 23:39:19 +01:00
// apart from the string being built-up, which could easily be replaced
// with a file stream (although I've chosen not to do that just yet).
//
2012-03-31 11:16:13 +02:00
// Writes nicely 2-space indented output with correct comma-placement
2012-03-27 23:25:04 +02:00
// in arrays and dictionaries.
//
// Does not deal with encodings in any way.
//
// Zero dependencies apart from stdlib (if you remove the vhjson usage.)
2012-03-24 23:39:19 +01:00
#include <string>
#include <vector>
#include <sstream>
class JsonWriter {
2012-05-08 22:04:24 +02:00
public:
JsonWriter(int flags = NORMAL);
2012-10-30 13:20:55 +01:00
~JsonWriter();
void begin();
void beginArray();
void beginRaw();
2012-10-30 13:20:55 +01:00
void end();
void pushDict();
2012-10-30 13:20:55 +01:00
void pushDict(const char *name);
void pushArray();
2012-10-30 13:20:55 +01:00
void pushArray(const char *name);
void pop();
void writeBool(bool value);
void writeBool(const char *name, bool value);
void writeInt(int value);
void writeInt(const char *name, int value);
void writeFloat(double value);
void writeFloat(const char *name, double value);
void writeString(const char *value);
void writeString(const char *name, const char *value);
void writeString(const std::string &value) {
writeString(value.c_str());
}
void writeString(const char *name, const std::string &value) {
writeString(name, value.c_str());
}
void writeString(const std::string &name, const std::string &value) {
writeString(name.c_str(), value.c_str());
}
void writeRaw(const char *value);
void writeRaw(const char *name, const char *value);
void writeRaw(const std::string &value) {
writeRaw(value.c_str());
}
void writeRaw(const char *name, const std::string &value) {
writeRaw(name, value.c_str());
}
void writeRaw(const std::string &name, const std::string &value) {
writeRaw(name.c_str(), value.c_str());
}
2012-03-24 23:39:19 +01:00
2012-10-30 13:20:55 +01:00
std::string str() const {
return str_.str();
}
2012-03-24 23:39:19 +01:00
enum {
NORMAL = 0,
PRETTY = 1,
};
2012-05-08 22:04:24 +02:00
private:
2012-10-30 13:20:55 +01:00
const char *indent(int n) const;
const char *comma() const;
const char *arrayComma() const;
const char *indent() const;
const char *arrayIndent() const;
void writeEscapedString(const char *s);
2012-10-30 13:20:55 +01:00
enum BlockType {
ARRAY,
DICT,
RAW,
2012-10-30 13:20:55 +01:00
};
struct StackEntry {
StackEntry(BlockType t) : type(t), first(true) {}
BlockType type;
bool first;
};
std::vector<StackEntry> stack_;
std::ostringstream str_;
bool pretty_;
2012-03-24 23:39:19 +01:00
};
struct json_value;
std::string json_stringify(const json_value *json);