From a77c5a61a6c7ecce0325bbf5cb4e45f767271d1e Mon Sep 17 00:00:00 2001 From: guonaihong Date: Mon, 13 Mar 2023 23:40:42 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E6=96=87=E6=A1=A3=20(#7)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 24 ++++++++++++++++++++++++ json/json_ex_test.go | 4 ++-- option/option.go | 4 +++- 3 files changed, 29 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index ec823ba..e377431 100644 --- a/README.md +++ b/README.md @@ -321,3 +321,27 @@ getValue := map[string]any{ _, err := json.Marshal([]byte(obj), option.WithStructName("reqName"), option.WithTagName("json"), option.WithGetRawValue(getValue)) fmt.Println(getValue[".a"], "b")) ``` +### 2.6 option.WithUsePtrType 支持(json/yaml) +```go +obj := ` +{ + "string": "", + "int": 0, + "float64": 3.1415, + "bool": false +} +` +ptrField := []string{".string", ".int", ".float64", ".bool"} //指定字段名使用指针类型 + +all, err := json.Marshal([]byte(obj), option.WithStructName("reqName"), option.WithGetRawValue(ptrField)) +fmt.Printf("%s\n", all) +// 输出: +/* +type reqName struct { + Bool *bool `json:"bool"` + Float64 *float64 `json:"float64"` + Int *int `json:"int"` + String *string `json:"string"` +} +*/ +``` diff --git a/json/json_ex_test.go b/json/json_ex_test.go index 9323e09..540b169 100644 --- a/json/json_ex_test.go +++ b/json/json_ex_test.go @@ -64,11 +64,11 @@ func Test_Gen_Obj_JSONEx(t *testing.T) { assert.Equal(t, need1, got1) assert.Equal(t, need2, got2) - gotPtr1, err := Marshal(data, option.WithStructName("reqName"), option.WithOutputFmtBefore(&out), option.WithUsePtrField(keys)) + gotPtr1, err := Marshal(data, option.WithStructName("reqName"), option.WithOutputFmtBefore(&out), option.WithUsePtrType(keys)) assert.NoError(t, err, out.String()) out.Reset() - gotPtr2, err := Marshal(data, option.WithStructName("reqName"), option.WithNotInline(), option.WithOutputFmtBefore(&out), option.WithUsePtrField(keys)) + gotPtr2, err := Marshal(data, option.WithStructName("reqName"), option.WithNotInline(), option.WithOutputFmtBefore(&out), option.WithUsePtrType(keys)) assert.NoError(t, err, out.String()) needPtr1 = bytes.TrimSpace(needPtr1) diff --git a/option/option.go b/option/option.go index adaa148..7c7af00 100644 --- a/option/option.go +++ b/option/option.go @@ -115,8 +115,10 @@ func WithProtobuf() OptionFunc { } } +// 传入的字段使用指针类型 +// 入参[]string{".字段名1", ".字段名2"} // json/yaml有效 -func WithUsePtrField(fieldList []string) OptionFunc { +func WithUsePtrType(fieldList []string) OptionFunc { return func(c *Option) { if c.UsePtr == nil { c.UsePtr = make(map[string]bool)