我試圖解析此JSON文檔: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()'。 –
如果你有一個最近的'valac'和'json-glib-1.0'軟件包,你也可以使用'Json.from_string()'。它也會爲你節省一些LOC。 –