ppsspp/json/json_writer.h

61 lines
1.5 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.
//
2012-03-24 23:39:19 +01:00
// Zero dependencies apart from stdlib.
2012-03-31 11:16:13 +02:00
// See json_writer_test.cpp for usage.
2012-03-24 23:39:19 +01:00
#include <string>
#include <vector>
#include <sstream>
#include "base/basictypes.h"
class JsonWriter {
2012-05-08 22:04:24 +02:00
public:
2012-03-24 23:39:19 +01:00
JsonWriter();
~JsonWriter();
void begin();
void end();
void pushDict(const char *name);
void pushArray(const char *name);
2012-05-08 22:04:24 +02:00
void pop();
2012-03-24 23:39:19 +01:00
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);
std::string str() const {
return str_.str();
}
2012-05-08 22:04:24 +02:00
private:
2012-03-24 23:39:19 +01:00
const char *indent(int n) const;
const char *comma() const;
const char *arrayComma() const;
const char *indent() const;
const char *arrayIndent() const;
enum BlockType {
ARRAY,
DICT,
};
struct StackEntry {
StackEntry(BlockType t) : type(t), first(true) {}
BlockType type;
bool first;
};
std::vector<StackEntry> stack_;
std::ostringstream str_;
2012-05-08 22:04:24 +02:00
DISALLOW_COPY_AND_ASSIGN(JsonWriter);
2012-03-24 23:39:19 +01:00
};