【发布时间】:2020-04-28 14:59:59
【问题描述】:
我正在尝试转换表单的json
{
"content": {
"test_key": "test"
},
"sender": "alice",
"type": "key_type"
}
我的对象是
template<class Content>
struct Event
{
Content content;
std::string type;
};
正在使用模板,因为内容的结构不固定。当我尝试使用 from_json 时,就像
template<class Content>
void
from_json(const nlohmann::json &obj, Event<Content> &event)
{
event.content = obj.at("content").get<Content>();
event.type = obj.at("type").get<std::string>();
}
我收到了错误
[json.exception.out_of_range.403] 未找到键“内容”
虽然 json 中有内容键。为什么会这样?
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
using namespace std;
template<typename Content>
struct Event
{
Content content;
string type;
};
template<typename Content>
void from_json(const nlohmann::json &obj, Event<Content> &event)
{
event.content = obj.at("content").get<Content>();
event.type = obj.at("type").get<string>();
}
struct Key{
string test_key;
string random_data;
};
int main(){
json j={{"content",{{"test_key","test"}}},{"sender","alice"},{"type","key_type"}};
Event<Key> event_instance;
try{
from_json(j,event_instance);
}
catch(json::exception& e){
cout<<e.what()<<endl;
}
}
上面的代码是一个最小可重现的例子
【问题讨论】:
-
@TedLyngmo 我想我会详细说明以便于理解 for_json 函数第一个参数是第一个 sn-p 中提到的 json,第二个参数是第二个 sn-p 中的类的一个实例。在将这些参数传递给函数时,我收到了这个错误。希望现在看起来没问题。
标签: c++ json nlohmann-json