[英]Boost read_json is not working with wptree from std::wstring
I have a simple code which is not working and I don't really know why... here it's:我有一个不起作用的简单代码,我真的不知道为什么......这里是:
std::wstring CDbFilterSerializer::DeserializeFromString(const std::wstring& jsonStr)
{
std::wistringstream ss{ jsonStr };
boost::property_tree::read_json(ss, m_root);
return m_root.data();
}
The problem here is that after calling m_root.read_json(...) the wptre object is empty.这里的问题是在调用m_root.read_json(...)之后 wptre object 是空的。 The return statement is an example, cause the real code after populating the wptree object, I call m_root.get("MyKey") to start reading values and this throw an exception cause the object is empty.
return 语句是一个示例,导致实际代码填充 wptree object 后,我调用 m_root.get("MyKey") 开始读取值,这引发异常导致 object 为空。
The json received as parameter is:作为参数接收的 json 是:
{
"type":{
"className":"NumericFilterSerializerHelper: NumericType => unsigned int, DbSerializer => class CDbFilterSerializerByNumericValue",
"description":""
},
"data":{
"int_number":"45"
}
}
Is there something wrong here?这里有什么问题吗?
Yes.是的。 The assumptions are wrong.
假设是错误的。
.data()
returns the value at the root node, which is empty (since it's an object). .data()
返回根节点的值,它是空的(因为它是一个对象)。 You can print the entire m_tree
to see:您可以打印整个
m_tree
以查看:
#include <boost/property_tree/json_parser.hpp>
#include <iostream>
struct CDbFilterSerializer {
std::wstring DeserializeFromString(const std::wstring& jsonStr);
boost::property_tree::wptree m_root;
};
std::wstring CDbFilterSerializer::DeserializeFromString(const std::wstring& jsonStr)
{
std::wistringstream ss{ jsonStr };
read_json(ss, m_root);
return m_root.data();
}
int main() {
CDbFilterSerializer obj;
obj.DeserializeFromString(LR"({
"type":{
"className":"NumericFilterSerializerHelper: NumericType => unsigned int, DbSerializer => class CDbFilterSerializerByNumericValue",
"description":""
},
"data":{
"int_number":"45"
}
})");
write_json(std::wcout, obj.m_root, true);
}
Which prints哪个打印
{
"type": {
"className": "NumericFilterSerializerHelper: NumericType => unsigned int, DbSerializer => class CDbFilterSerializerByNumericVa
lue",
"description": ""
},
"data": {
"int_number": "45"
}
}
As you can see the object is not empty.如您所见,object不为空。 You probably have the path misspelled (we can't tell because
MyKey
is not in your document).您可能拼错了路径(我们无法判断,因为
MyKey
不在您的文档中)。
Do not abuse Property Tree for JSON "support".不要滥用 JSON“支持”的属性树。 Instead use a JSON library.
而是使用 JSON 库。 Boost JSON exists.
升压 JSON 存在。 Several others are freely available.
其他几个是免费的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.