我正在尝试解析这个JSON文档:
{
"registration" : "F-FBZH",
"model" : "DR400-120"
}
这是我制作的内容:
public Plane load_airplane (string registration) {
try {
string? res = null;
var file = File.new_for_path (location + registration + ".json");
if (file.query_exists ()) {
var dis = new DataInputStream (file.read ());
string line;
while ((line = dis.read_line (null)) != null) {
res += line;
}
var parser = new Json.Parser ();
parser.load_from_data (res);
var root_object = parser.get_root ().get_object ();
string data_registration = root_object.get_string_member ("registration");
string data_model = root_object.get_string_member ("model");
return new Plane (data_registration, data_model);
}
} catch (Error e) {
stderr.printf ("%s\n", e.message);
}
return new Plane.default ();
}
代码编译没有问题,但是当我运行程序时出现了以下错误:
(process:25868): Json-CRITICAL **: json_parser_load_from_data: assertion 'data != NULL' failed
(process:25868): Json-CRITICAL **: json_node_get_object: assertion 'JSON_NODE_IS_VALID (node)' failed
(process:25868): Json-CRITICAL **: json_object_get_string_member: assertion 'object != NULL' failed
(process:25868): Json-CRITICAL **: json_object_get_string_member: assertion 'object != NULL' failed
** (process:25868): CRITICAL **: open_plane_plane_construct: assertion 'registration != NULL' failed
** (process:25868): CRITICAL **: open_plane_plane_get_registration: assertion 'self != NULL' failed
(null)
为什么?又是一个问题,为什么使用中级语言Vala读取JSON这么难?这应该会更容易才对!
DataInputStream
,你可以直接调用file.load_contents()
。 - Jens Mühlenhoffvalac
和json-glib-1.0
软件包,也可以使用Json.from_string()
。这样做还可以节省一些代码行。 - Jens Mühlenhoff