Skip to content

Instantly share code, notes, and snippets.

@ubnt-intrepid
Last active September 17, 2015 19:40
Show Gist options
  • Select an option

  • Save ubnt-intrepid/328aa84dbcc99b4fea2e to your computer and use it in GitHub Desktop.

Select an option

Save ubnt-intrepid/328aa84dbcc99b4fea2e to your computer and use it in GitHub Desktop.
C++でGoのようなJSONアクセスを可能にする
#include <type_traits>
#include <iostream>
#include <string>
#include <boost/lexical_cast.hpp>
using boost::lexical_cast;
using namespace std;
struct key_value {
std::string value;
public:
char const* c_str() const { return value.c_str(); }
};
// T is default-constructible, copy assignable
template <typename T>
class val {
key_value name_;
T value_;
public:
// init member name
val(key_value name): name_{name} {}
val(T const& value, key_value name): name_{name}, value_(value) {}
val(T && value, key_value name): name_{name}, value_(std::move(value)) {}
val& operator=(T const& src) {
value_ = src;
return *this;
}
val& operator=(T && src) {
value_ = std::move(src);
return *this;
}
// get variable name in JSON
inline char const* name() const { return name_.c_str(); }
// get raw-reference of value
T& value() { return value_; }
T const& value() const { return value_; }
string to_s() const { return "\"" + name_ + "\":" + lexical_cast<string>(value_); }
};
struct Struct
{
val<int> foo{ 0, key_value{"foo"} }; // 第1引数にメンバの初期値,
val<string> bar{ "foo", key_value{"bar"} }; // 第2引数にJSONにおけるメンバ名を記載する
val<float> aaa{ key_value{"aaa"} }; // 初期値は省略可能
public:
Struct() = default;
Struct(int foo, string const& bar, float aaa)
{
this->foo = foo;
this->bar = bar;
this->aaa = aaa;
}
friend ostream& operator<<(ostream& os, Struct const& s) {
return os << "{" << s.foo.to_s() << "," << s.bar.to_s() << "," << s.aaa.to_s() << "}";
}
};
int main()
{
cout << Struct{} << endl;
Struct s1{ 1, "hoge", 0.01 };
cout << s1 << endl;
s1 = { 2, "fuga", 0.43 };
cout << s1 << endl;
}
import "encoding/json"
// Goだと構造体のメンバにこう書くことでJSONにおけるobjectとの相互変換が可能になる
type Member struct {
FirstName string `json::"first_name"`
LastName string `json::"last_name"`
Address string `json::"address"`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment