LoginSignup
3
0

More than 1 year has passed since last update.

Siv3DでJSON to Stringを実装した

Last updated at Posted at 2019-04-20

はじめに

OpenSiv3D v0.6.6時点では
JSONclassに統合され
標準でStringへの変換が可能になりました。

Format(json)

Siv3D とは

Siv3D

Siv3D は C++ で楽しく簡単にゲームやメディアアートを作れるライブラリです。

なお現在はOpenSiv3Dの開発がメインとなっており旧Siv3Dの開発は終了しています。

今回は旧Siv3Dでの実装ですが、OpenSiv3Dでも参考にすることはできます。

問題点

Siv3D/OpenSiv3DにはJSONReaderというクラスが用意されており簡単にJSONファイルをパースして使用することができます。

しかしJSONWriterはない

なので、ふと必要になった時に困ると思い簡単に実装してみた。

JSONエンコードの実装

JSONReaderでパースした際はJSONValue型で取得できるので、流用し
JSONValueからStringへの変換を実装する。

JSONEncode.hpp
#pragma once
#include<Siv3D/JSONValue.hpp>

namespace JSON
{
	s3d::String Encode(const s3d::JSONValue& json);
	void Encode(const s3d::JSONValue& json, s3d::String& out);
}
JSONEncode.cpp
#include "JSONEncode.hpp"
using namespace s3d;

namespace
{
	void Dump(const JSONValue& json, String& out);

	// json array
	void Dump(const JSONArray& json, String& out)
	{
		out += L"[";
		bool first = true;
		for (const auto& value : json) {
			if (!first) {
				out += L", ";
			}
			first = false;
			Dump(value, out);
		}
		out += L"]";
	}

	//json object
	void Dump(const JSONObject& json, String& out)
	{
		out += L"{";
		bool first = true;
		for (const auto& value : json) {
			if (!first) {
				out += L", ";
			}
			first = false;
			out += L'"' + value.first + L'"' + L": ";
			Dump(value.second, out);
		}
		out += L"}";
	}

	// json
	void Dump(const JSONValue& json, String& out)
	{
		if (json.isNull()) {
			out += L"null";
		}
		else if (json.isBool() || json.isNumber()) {
			out += json.to_str();
		}
		else if (json.isString()) {
			out += L'"' + json.getString() + L'"';
		}
		else if (json.isArray()) {
			Dump(json.getArray(), out);
		}
		else if (json.isObject()) {
			Dump(json.getObject(), out);
		}
	}
}

namespace JSON
{
	String Encode(const JSONValue& json)
	{
		String out;
		Encode(json, out);
		return out;
	}

	void Encode(const JSONValue& json, String& out)
	{
		::Dump(json, out);
	}
}

使ってみる

Main.cpp
#include <Siv3D.hpp>
#include "JSONEncode.hpp"

void Main()
{
	JSONObject json;
	json[L"number"] = JSONValue(1.0);
	json[L"bool"] = JSONValue(true);
	json[L"string"] = JSONValue(L"Hoge");
	json[L"array"] = JSONValue(JSONArray{ 
		JSONValue(0.1),
		JSONValue(L"Foo")
	});
	json[L"object"] = JSONValue(JSONObject{
		{L"key1",JSONValue(false)} ,
	});
	json[L"null"] = JSONValue(JSONValue::ValueType::Null, true);

	// 文字列型に変換
	String str = JSON::Encode(JSONValue(json));
	Println(str);
	WaitKey();
}

コンストラクタがexplicit指定されているため、ちょっと使いにくい…
(JSONValueに関してはラッパーを作ればもう少し楽にかける)

StringにできればTextWriterを使って、そのままjsonファイルとして書き出しもできます。

まとめ

  • JSONValueをStringに変換できた。
  • OpenSiv3DにJSON書き出し(to String)のほうも公式実装されると嬉しいなぁ
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0