// // json_binder_custom.t.h // json // // Created by Sam Jaffe on 9/12/17. // #pragma once #include #include "json/json_binder.hpp" #include using namespace json::binder; using namespace json::parser; class precision_binder : public binder_impl { public: precision_binder(int d) : digits(d), trunc(std::pow(10, d)) {} virtual ~precision_binder() = default; binder_impl * clone() const override { return new precision_binder{*this}; } void parse(double & value, char const * & str, options) const override { std::sscanf(str, "%lf", &value); value = static_cast(value * trunc) / trunc; json::parse_discard_token(str); // Advance to the boundary } void write(double const & value, std::ostream & out) const override { out << std::fixed << std::setprecision(digits) << value; } private: int digits; double trunc; }; class json_binder_custom_TestSuite : public CxxTest::TestSuite { public: struct TestObject { double A; // four_digits double B; // two_digits double C; bool operator==(TestObject const & other) const { return A == other.A && B == other.B && C == other.C; } }; static object_binder GetImpl() { return object_binder() ("A", &TestObject::A, precision_binder(4)) ("B", &TestObject::B, precision_binder(2)) ("C", &TestObject::C); } static object_binder & Get() { static object_binder val = GetImpl(); return val; } void test_() { char data[] = "{\"A\":1.00008, \"B\":1.0, \"C\":1.523211102}"; TestObject out{0.0, 0.0, 0.0}; TestObject const expected{1.0, 1.0, 1.523211102}; TS_ASSERT_THROWS_NOTHING(parse(json::binder::bind(out, Get()), data)); TS_ASSERT_EQUALS(out, expected); } };