Set id when creating Item from JSON
This commit is contained in:
parent
3032957071
commit
52a626fe12
18
src/Item.zig
18
src/Item.zig
|
@ -91,11 +91,12 @@ pub fn fromJson(jobj: json.Obj, allocator: std.mem.Allocator) !Self {
|
||||||
// Try to assemble a Item object from a JSON string
|
// Try to assemble a Item object from a JSON string
|
||||||
// An item could be just an id, just tags or both.
|
// An item could be just an id, just tags or both.
|
||||||
|
|
||||||
var opt_jtags = jobj.objectGet("tags") catch null;
|
|
||||||
var tags: ?[]Tag = null;
|
var tags: ?[]Tag = null;
|
||||||
|
|
||||||
if (opt_jtags) |*jtags| {
|
if (jobj.objectGet("tags") catch null) |*jtags| {
|
||||||
defer jtags.deinit();
|
defer jtags.deinit();
|
||||||
|
|
||||||
|
// Reserve space for slice of tags
|
||||||
const len = @intCast(usize, jtags.objectLen());
|
const len = @intCast(usize, jtags.objectLen());
|
||||||
tags = try allocator.alloc(Tag, len);
|
tags = try allocator.alloc(Tag, len);
|
||||||
|
|
||||||
|
@ -111,8 +112,19 @@ pub fn fromJson(jobj: json.Obj, allocator: std.mem.Allocator) !Self {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var id: ?i64 = null;
|
||||||
|
|
||||||
|
if (jobj.objectGet("id") catch null) |*jid| {
|
||||||
|
defer jid.deinit();
|
||||||
|
|
||||||
|
id = jid.getInt64();
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: What should be done when both things are null?
|
||||||
|
// Return a null Obj or leave it as-is?
|
||||||
|
|
||||||
return Self{
|
return Self{
|
||||||
.id = null,
|
.id = id,
|
||||||
.tags = tags,
|
.tags = tags,
|
||||||
.allocator = allocator,
|
.allocator = allocator,
|
||||||
};
|
};
|
||||||
|
|
|
@ -56,6 +56,10 @@ pub const Obj = struct {
|
||||||
// TODO: Check type to not allow other types
|
// TODO: Check type to not allow other types
|
||||||
return std.mem.sliceTo(c.json_object_get_string(self.obj), 0);
|
return std.mem.sliceTo(c.json_object_get_string(self.obj), 0);
|
||||||
}
|
}
|
||||||
|
pub fn getInt64(self: Obj) i64 {
|
||||||
|
// TODO: Check ERRNO to see if there was an error
|
||||||
|
return c.json_object_get_int64(self.obj);
|
||||||
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *Obj) void {
|
pub fn deinit(self: *Obj) void {
|
||||||
_ = c.json_object_put(self.obj);
|
_ = c.json_object_put(self.obj);
|
||||||
|
|
Loading…
Reference in New Issue