【问题标题】:Parse JSON with Vala使用 Vala 解析 JSON
【发布时间】:2016-05-29 15:11:10
【问题描述】:

我正在尝试解析这个 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 ()即可。
  • 如果您最近安装了valacjson-glib-1.0 软件包,您也可以使用Json.from_string ()。它还会为您节省一些 LOC。

标签: json glib vala


【解决方案1】:

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

如果你在字符串中添加一些东西,它将保持为空。

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

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-12
  • 2013-06-24
  • 2018-09-12
  • 2012-01-02
  • 2013-12-25
相关资源
最近更新 更多