Skip to content

Commit

Permalink
Implement JValue.toString - serializes the object into a JSON-formatt…
Browse files Browse the repository at this point in the history
…ed string. #5
  • Loading branch information
SilverIce committed Sep 4, 2019
1 parent 255f512 commit 84b41c3
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
12 changes: 11 additions & 1 deletion JContainers/src/api_3/tes_object.h
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,17 @@ JValue.cleanPool(\"uniquePoolName\")"
auto obj = json_deserializer::object_from_json_data( ctx, prototype);
return obj;
}
REGISTERF2(objectFromPrototype, "prototype", "Creates a new container object using given JSON string-prototype");
REGISTERF2(objectFromPrototype, "prototype", "Creates a new container object using given JSON string");

static skse::string_ref toString(tes_context& ctx, object_base* obj, SInt32 json_indent = 2) {
if (!obj) {
return {};
}
auto json = json_serializer::create_json_data(*obj, util::to_enum<json_serializer::indent_t>(json_indent));
return { json.get() };
}
REGISTERF2(toString, "* indentation=2", "Serializes the object into a JSON-formatted string.\n"
"Indentation affects JSON text formatting. The output string is most compact with indentation = -1");

static void writeToFile(tes_context& ctx, object_base *obj, const char * cpath) {
if (!cpath || !obj) {
Expand Down
11 changes: 9 additions & 2 deletions JContainers/src/collections/json_serialization.h
Original file line number Diff line number Diff line change
Expand Up @@ -369,12 +369,19 @@ namespace collections {
return make_unique_ptr( json_serializer(root)._write_json(root), &json_decref);
}

static auto create_json_data(const object_base &root) -> decltype(make_unique_ptr((char*)nullptr, free)) {
enum class indent_t : int32_t {
compact = -1,
// the rest of values mean any json output text indent >= 0
default = 2,
};

static auto create_json_data(const object_base& root, indent_t indent = indent_t::default) -> decltype(make_unique_ptr((char*)nullptr, free)) {

auto jvalue = create_json_value(root);

auto indentation = indent != indent_t::compact ? JSON_INDENT(util::to_integral(indent)) : JSON_COMPACT;
return make_unique_ptr(
jvalue ? json_dumps(jvalue.get(), JSON_INDENT(2)) : nullptr,
jvalue ? json_dumps(jvalue.get(), indentation) : nullptr,
free
);
}
Expand Down

0 comments on commit 84b41c3

Please sign in to comment.