diff --git a/compiler/jsgen.v b/compiler/jsgen.v index b3ef5cd209..3c7d9ef725 100644 --- a/compiler/jsgen.v +++ b/compiler/jsgen.v @@ -85,15 +85,17 @@ string res = tos2(""); if field.attr == 'skip' { continue } - + name := if field.attr.starts_with('json:') { + field.attr.right(5) + } else { + field.name + } field_type := p.table.find_type(field.typ) - name := field.name _typ := field.typ.replace('*', '') - enc_name := js_enc_name(_typ) - if field.attr == 'raw' { - dec += ' /*prim*/ res->$name = tos2(cJSON_PrintUnformatted(js_get(root, "$field.name")));\n' + dec += ' res->$field.name = tos2(cJSON_PrintUnformatted(' + + 'js_get(root, "$name")));\n' } else { // Now generate decoders for all field types in this struct @@ -103,16 +105,15 @@ string res = tos2(""); dec_name := js_dec_name(_typ) if is_js_prim(_typ) { - dec += ' /*prim*/ res->$name = $dec_name(js_get(root, "$field.name"))' - // dec += '.data' + dec += ' res->$field.name = $dec_name(js_get(' + + 'root, "$name"))' } else { - dec += ' /*!!*/ $dec_name(js_get(root, "$field.name"), & (res->$name))' + dec += ' $dec_name(js_get(root, "$name"), & (res->$name))' } dec += ';\n' } - - enc += ' cJSON_AddItemToObject(o, "$name", $enc_name(val.$name)); \n' + enc += ' cJSON_AddItemToObject(o, "$name",$enc_name(val.$field.name)); \n' } // cJSON_delete //p.cgen.fns << '$dec return opt_ok(res); \n}' diff --git a/compiler/parser.v b/compiler/parser.v index eb0eefcfed..db47a23384 100644 --- a/compiler/parser.v +++ b/compiler/parser.v @@ -645,6 +645,10 @@ fn (p mut Parser) struct_decl() { if p.tok == .lsbr { p.next() attr = p.check_name() + if p.tok == .colon { + p.check(.colon) + attr += ':' + p.check_name() + } p.check(.rsbr) } if attr == 'raw' && field_type != 'string' { diff --git a/vlib/json/json_test.v b/vlib/json/json_test.v index 9d0acf35de..e2f32558ff 100644 --- a/vlib/json/json_test.v +++ b/vlib/json/json_test.v @@ -1,20 +1,22 @@ -import json +import json struct User { - age int - nums []int + age int + nums []int + last_name string [json:lastName] } fn test_parse_user() { - s := '{"age": 10, "nums": [1,2,3]}' + s := '{"age": 10, "nums": [1,2,3], "lastName": "Johnson"}' u := json.decode(User, s) or { - exit(1) + exit(1) } assert u.age == 10 + assert u.last_name == 'Johnson' assert u.nums.len == 3 - assert u.nums[0] == 1 - assert u.nums[1] == 2 - assert u.nums[2] == 3 + assert u.nums[0] == 1 + assert u.nums[1] == 2 + assert u.nums[2] == 3 } struct Color {