Skip to content

How to use value for std::experimental::optional type? #760

Description

@dianambb

I am trying to parse the json value for a field if it exists and set it to std::experimental::nullopt if it does not.

#include "json.hpp"
#include <experimental/optional>

namespace nlohmann {
    template <typename T>
    struct adl_serializer<std::experimental::optional<T>> {
        static void to_json(json& j, const std::experimental::optional<T>& opt) {
            if (opt == std::experimental::nullopt) {
                j = nullptr;
            } else {
                j = *opt;
            }
        }
        
        static void from_json(const json& j, std::experimental::optional<T>& opt) {
            if (j.is_null()) {
                opt = std::experimental::nullopt;
            } else {
                opt = j.get<T>();
            }
        }
    };
}

namespace my_project {
struct Person {
    std::string id;
    std::string name;
    std::experimental::optional<std::string> company;
};

    void to_json(json& j, const Person& p) {
        j = json {
            {"id", p.id},
            {"name", p.name},
            {"company", p.company}
        };
    }
    
    void from_json(const json& j, Person& p) {
        p.id = j.at("id").get<std::string>();
        p.name = j.at("name").get<std::string>();

        // This works

        try {
            p.company = j.at("company").get<std::experimental::optional<std::string>>();
        } catch(std::exception) {
            p.company = std::experimental::nullopt;
        }

        // This does not work, but it would be nice to have it instead if using try/catch for multiple fields.

        p.company = j.value("company", std::experimental::nullopt);
    }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions