json: minor fixes + bring back the test

pull/4716/head
Alexander Medvednikov 2020-05-04 20:43:22 +02:00
parent 6e1825b417
commit 9823d80e0c
3 changed files with 26 additions and 4 deletions

View File

@ -7,7 +7,6 @@ import v.pref
const (
skip_test_files = [
'vlib/arrays/arrays_test.v',
'vlib/json/json_test.v',
'vlib/v/tests/enum_bitfield_test.v',
'vlib/v/tests/num_lit_call_method_test.v',
'vlib/v/tests/pointers_test.v',

View File

@ -1,5 +1,22 @@
import json
struct Employee {
name string
age int
}
fn test_simple() {
x := Employee{'Peter', 28}
s := json.encode(x)
assert s == '{"name":"Peter","age":28}'
y := json.decode(Employee, s) or {
assert false
}
assert y.name == 'Peter'
assert y.age == 28
}
/*
struct User {
age int
nums []int
@ -43,3 +60,4 @@ fn test_raw_json_field() {
assert color.point == '{"Y":123}'
assert color.space == 'YCbCr'
}
*/

View File

@ -25,6 +25,9 @@ fn (mut g Gen) gen_json_for_type(typ table.Type) {
if sym.name in ['int', 'string', 'bool'] {
return
}
if sym.kind == .array {
return
}
// println('gen_json_for_type($typ.name)')
// decode_TYPE funcs receive an actual cJSON* object to decode
// cJSON_Parse(str) call is added by the compiler
@ -55,6 +58,9 @@ cJSON* ${enc_fn_name}($styp val) {
// enc += p.encode_array(t)
}
// Range through fields
if !(sym.info is table.Struct) {
verror('json: $sym.name is not struct')
}
info := sym.info as table.Struct
for field in info.fields {
if field.attr == 'skip' {
@ -71,11 +77,10 @@ cJSON* ${enc_fn_name}($styp val) {
g.gen_json_for_type(field.typ)
dec_name := js_dec_name(field_type)
if is_js_prim(field_type) {
dec.writeln(' res . $field.name = $dec_name (js_get(' + 'root, "$name"))')
dec.writeln(' res . $field.name = $dec_name (js_get(' + 'root, "$name"));')
} else {
dec.writeln(' $dec_name (js_get(root, "$name"), & (res->$field.name))')
dec.writeln(' $dec_name (js_get(root, "$name"), & (res . $field.name));')
}
dec.writeln(';')
}
enc.writeln('\tcJSON_AddItemToObject(o, "$name", ${enc_name}(val.$field.name));')
}