在 Vala 中使用 json-glib-1.0 访问字典?
Access a dictionary with json-glib-1.0 in Vala?
我正在尝试使用 json-glib 访问 json 字典,但我不知道如何按照 Valadoc
访问它
我正在尝试访问 files
,字典看起来像这样:
"items": [
{
"kind": "webfonts#webfont",
"family": "ABeeZee",
"category": "sans-serif",
"variants": [
"regular",
"italic"
],
"subsets": [
"latin"
],
"version": "v12",
"lastModified": "2019-04-29",
"files": {
"regular": "http://fonts.gstatic.com/s/abeezee/v12/esDR31xSG-6AGleN6tKukbcHCpE.ttf",
"italic": "http://fonts.gstatic.com/s/abeezee/v12/esDT31xSG-6AGleN2tCklZUCGpG-GQ.ttf"
}
},
有人可以帮忙吗?
您可以使用 GObject
的反序列化功能:
public class Obj : Object {
public string kind { get; set; }
public string family { get; set; }
public string category { get; set; }
public string[] variants { get; set; }
public int num { get; set; }
public string to_string () {
StringBuilder builder = new StringBuilder ();
builder.append_printf ("kind = %s\n", kind);
builder.append_printf ("family = %s\n", family);
builder.append_printf ("category = %s\n", category);
builder.append_printf(@"variants:[\n");
foreach (var item in variants)
builder.append_printf(@"\t$item\n");
builder.append_printf(@"]\n");
return (owned) builder.str;
}
}
void main (string[] args) {
string data = """
{
"kind" : "my string",
"family" : "ABeeZee",
"category" : "sans-serif",
"variants": [
"regular",
"italic"
]
}""";
var obj = Json.gobject_from_data (typeof (Obj), data) as Obj;
print (@"$obj");
}
这将输出:
> vala console.vala --pkg json-glib-1.0
kind = my string
family = ABeeZee
category = sans-serif
variants:[
regular
italic
]
我正在尝试使用 json-glib 访问 json 字典,但我不知道如何按照 Valadoc
访问它我正在尝试访问 files
,字典看起来像这样:
"items": [
{
"kind": "webfonts#webfont",
"family": "ABeeZee",
"category": "sans-serif",
"variants": [
"regular",
"italic"
],
"subsets": [
"latin"
],
"version": "v12",
"lastModified": "2019-04-29",
"files": {
"regular": "http://fonts.gstatic.com/s/abeezee/v12/esDR31xSG-6AGleN6tKukbcHCpE.ttf",
"italic": "http://fonts.gstatic.com/s/abeezee/v12/esDT31xSG-6AGleN2tCklZUCGpG-GQ.ttf"
}
},
有人可以帮忙吗?
您可以使用 GObject
的反序列化功能:
public class Obj : Object {
public string kind { get; set; }
public string family { get; set; }
public string category { get; set; }
public string[] variants { get; set; }
public int num { get; set; }
public string to_string () {
StringBuilder builder = new StringBuilder ();
builder.append_printf ("kind = %s\n", kind);
builder.append_printf ("family = %s\n", family);
builder.append_printf ("category = %s\n", category);
builder.append_printf(@"variants:[\n");
foreach (var item in variants)
builder.append_printf(@"\t$item\n");
builder.append_printf(@"]\n");
return (owned) builder.str;
}
}
void main (string[] args) {
string data = """
{
"kind" : "my string",
"family" : "ABeeZee",
"category" : "sans-serif",
"variants": [
"regular",
"italic"
]
}""";
var obj = Json.gobject_from_data (typeof (Obj), data) as Obj;
print (@"$obj");
}
这将输出:
> vala console.vala --pkg json-glib-1.0
kind = my string
family = ABeeZee
category = sans-serif
variants:[
regular
italic
]