瀏覽代碼

Add support of `ignore` tag for `json.marshal`

VladPavliuk 1 年之前
父節點
當前提交
64ae99f016
共有 2 個文件被更改,包括 24 次插入1 次删除
  1. 3 1
      core/encoding/json/marshal.odin
  2. 21 0
      tests/core/encoding/json/test_core_json.odin

+ 3 - 1
core/encoding/json/marshal.odin

@@ -406,7 +406,7 @@ marshal_to_writer :: proc(w: io.Writer, v: any, opt: ^Marshal_Options) -> (err:
 			ti := runtime.type_info_base(type_info_of(v.id))
 			info := ti.variant.(runtime.Type_Info_Struct)
 			first_iteration := true
-			for name, i in info.names {
+			fields_loop: for name, i in info.names {
 				omitempty := false
 
 				json_name, extra := json_name_from_tag_value(reflect.struct_tag_get(reflect.Struct_Tag(info.tags[i]), "json"))
@@ -414,6 +414,8 @@ marshal_to_writer :: proc(w: io.Writer, v: any, opt: ^Marshal_Options) -> (err:
 					switch flag {
 					case "omitempty":
 						omitempty = true
+					case "ignore":
+						continue fields_loop
 					}
 				}
 

+ 21 - 0
tests/core/encoding/json/test_core_json.odin

@@ -368,4 +368,25 @@ utf8_string_of_multibyte_characters :: proc(t: ^testing.T) {
 	val, err := json.parse_string(`"🐛✅"`)
 	defer json.destroy_value(val)
 	testing.expectf(t, err == nil, "Expected `json.parse` to return nil, got %v", err)
+}
+
+@test
+struct_with_ignore_tags :: proc(t: ^testing.T) {
+	My_Struct :: struct {
+		a: string `json:"_,ignore"`,
+	}
+
+	my_struct := My_Struct{
+		a = "test",
+	}
+
+	my_struct_marshaled, marshal_err := json.marshal(my_struct)
+	defer delete(my_struct_marshaled)
+
+	testing.expectf(t, marshal_err == nil, "Expected `json.marshal` to return nil error, got %v", marshal_err)
+
+	my_struct_json := transmute(string)my_struct_marshaled
+	expected_json := `{}`
+
+	testing.expectf(t, expected_json == my_struct_json, "Expected `json.marshal` to return %s, got %s", expected_json, my_struct_json)
 }