用 Vala 解析 JSON

Parse JSON with Vala

我正在尝试解析此 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 这么难?应该会容易很多!

问题是您正在将可为 null 的 res 字符串初始化为 null。

如果您随后向该字符串添加内容,它将保持为空。

string? res = null;
res += "something";
// res will still be null here!

您可以将其初始化为 ""(空字符串,在这种情况下您也可以只使用不可为 null 的字符串)或者您可以跳过 DataInputStream 并使用 file.load_contents ().