as the object
i think it’s a stupid question, but i cannot find the way
i tried with json_reader_get_value but it returns an error “The current position holds a “jsonobject” and not a value”
as the object
i think it’s a stupid question, but i cannot find the way
i tried with json_reader_get_value but it returns an error “The current position holds a “jsonobject” and not a value”
You don’t access JsonObject
and JsonArray
directly with JsonReader
; instead, you’re supposed to “enter” an object, and then leave it.
For instance, given something like:
[
{ "foo": "bar", "baz": true },
{ "foo": "hello", "baz": false }
]
Your reader instance can be used like this:
// Assert that the element is an array
g_assert_true (json_reader_is_array (reader));
// Read the first element of the array
json_reader_read_element (reader, 0);
// Assert that the element contains an object
g_assert_true (json_reader_is_object (reader));
// Enter the "foo" member of the object
json_reader_read_member (reader, "foo")
foo[0] = json_reader_get_string_value (reader);
json_reader_end_member (reader);
// Enter the "bar" member of the object
json_reader_read_member (reader, "bar");
bar[0] = json_reader_get_boolean_value (reader);
json_reader_end_member (reader);
// Leave the first element of the array
json_reader_end_element (reader);
// Enter the second element
json_reader_read_element (reader, 1);
// Repeat…
The JsonReader
object is used to consume the object model while traversing it; if you want to access the actual data types, then you should use the JsonNode
API.
sorry i forgot to provide the json
{
"object_a": {"id": 4, "name": "foo" },
"object_b": {"color": "red", "model":"supreme"}
}
and the code
json_reader_read_element (reader, 0);
json_reader_get_member_name (reader); // ok it returns "object_a"
json_reader_is_object (reader); // ok it returns true
json_reader_get_value (reader); // error: The current position holds a “jsonobject” and not a value
so i cannot get object_a.id (or name)
Yes, you’re trying to get the JsonObject
, which is not possible with JsonReader
. You’re supposed to enter the nested object and retrieve its members, e.g.
json_reader_read_member (reader, "object_a");
json_reader_read_member (reader, "id");
gint64 id = json_reader_get_int_value (reader); // id = 4
json_reader_end_member (reader); // leaves "id"
json_reader_read_member (reader, "name");
const char *name = json_reader_get_string_value (reader); // name = "foo"
json_reader_end_member (reader); // leaves "name"
json_reader_end_member (reader); // leaves "object_a"
json_reader_read_member (reader, "object_b");
// read members of "object_b"
json_reader_end_member (reader); // leaves "object_b"
ok, clear, thank you
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.