I'm using jsoncpp parser (http://jsoncpp.sourceforge.net) to parse JSON data. So, if we have the following JSON:
我正在使用jsoncpp解析器(http://jsoncpp.sourceforge.net)来解析JSON数据。所以,如果我们有以下JSON:
{ "name": "Joseph", "age": 20 }
How can I get the property name name and value Joseph, ... after age and 20? OK, we can do universally this:
如何获得属性名称和值Joseph,...年龄20岁以后?好的,我们可以普遍做到这一点:
string e = root.get(propertyName, defaultValue).asString();
Put real what we want:
把我们想要的东西:
string e = root.get(name, "Mark").asString();
Now, variable e is Joseph, it works. But I have to take/write "name". I do not want to QUERY (without questioning the function I want to get "name" (name of property) and "Joseph" (value of property)).
现在,变量e是约瑟夫,它有效。但我必须采取/写“名字”。我不想查询(没有质疑我想得到的功能“name”(属性名称)和“Joseph”(属性值))。
After it would be best to store in a field (C/C++ for example):
之后最好存储在一个字段中(例如C / C ++):
property[name][0] = "Joseph"
property[age][0] = 20
How can I do that? Or any other ideas?
我怎样才能做到这一点?还是其他任何想法?
1 个解决方案
#1
6
You can get all the member names of a Json::Value object using its getMemberNames()
function. That returns an object that you can iterate over using .begin()
and .end()
, like any other standard library container. (In fact, the return type is an alias for std::vector<std::string>
.)
您可以使用其getMemberNames()函数获取Json :: Value对象的所有成员名称。这将返回一个对象,您可以使用.begin()和.end()进行迭代,就像任何其他标准库容器一样。 (实际上,返回类型是std :: vector
After you have the member names, you should be able to iterate through them and use .get(std::string &, const ValueType &)
as you already are doing to get the values for each of the object's keys.
拥有成员名称之后,您应该能够遍历它们并使用.get(std :: string&,const ValueType&),就像您已经在做的那样获取每个对象键的值。
Note that JSON objects are inherently unordered, so you can't necessarily rely on that name list having any ordering whatsoever. If you want an ordered object, you should be using JSON arrays, not JSON objects.
请注意,JSON对象本质上是无序的,因此您不一定要依赖具有任何排序的名称列表。如果需要有序对象,则应使用JSON数组,而不是JSON对象。
#1
6
You can get all the member names of a Json::Value object using its getMemberNames()
function. That returns an object that you can iterate over using .begin()
and .end()
, like any other standard library container. (In fact, the return type is an alias for std::vector<std::string>
.)
您可以使用其getMemberNames()函数获取Json :: Value对象的所有成员名称。这将返回一个对象,您可以使用.begin()和.end()进行迭代,就像任何其他标准库容器一样。 (实际上,返回类型是std :: vector
After you have the member names, you should be able to iterate through them and use .get(std::string &, const ValueType &)
as you already are doing to get the values for each of the object's keys.
拥有成员名称之后,您应该能够遍历它们并使用.get(std :: string&,const ValueType&),就像您已经在做的那样获取每个对象键的值。
Note that JSON objects are inherently unordered, so you can't necessarily rely on that name list having any ordering whatsoever. If you want an ordered object, you should be using JSON arrays, not JSON objects.
请注意,JSON对象本质上是无序的,因此您不一定要依赖具有任何排序的名称列表。如果需要有序对象,则应使用JSON数组,而不是JSON对象。