From 5a43ff8e200f4624cbc04949b787ee543a243cb2 Mon Sep 17 00:00:00 2001 From: gazebo Date: Mon, 19 Nov 2018 20:10:22 +0800 Subject: [PATCH] - Unmarshal2Map --- utils/typeconv.go | 18 ++++++++++++++++++ utils/utils_test.go | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/utils/typeconv.go b/utils/typeconv.go index d8229e6c..39c5edc1 100644 --- a/utils/typeconv.go +++ b/utils/typeconv.go @@ -13,6 +13,7 @@ import ( "time" "git.rosy.net.cn/baseapi" + "github.com/fatih/structs" ) var ( @@ -40,6 +41,23 @@ func UnmarshalUseNumber(data []byte, result interface{}) error { return err } +// 这个函数将解析json,返回的map中的字段类型与structObj中的完全一样的 +func Unmarshal2Map(data []byte, structObj interface{}) (resultMap map[string]interface{}, err error) { + if err = json.Unmarshal(data, structObj); err == nil { + if err = json.Unmarshal(data, &resultMap); err == nil { + m := structs.Map(structObj) + for k := range resultMap { + if value, ok := m[k]; ok { + resultMap[k] = value + } else { + delete(resultMap, k) + } + } + } + } + return resultMap, err +} + func MustMarshal(obj interface{}) []byte { byteArr, err := json.Marshal(obj) if err != nil { diff --git a/utils/utils_test.go b/utils/utils_test.go index 2c8ec914..e0809f7a 100644 --- a/utils/utils_test.go +++ b/utils/utils_test.go @@ -45,6 +45,46 @@ type TestModel2 struct { AddData string } +func TestUnmarshal2Map(t *testing.T) { + jsonStr := ` + { + "IntData" : 1, + "Int64Data" : 2, + "NotField" : "hello", + "StrData" : "world" + } + ` + var kk TestModel + result, err := Unmarshal2Map([]byte(jsonStr), &kk) + if err != nil { + t.Fatal("Unmarshal2Map error") + } + // t.Log(result) + if _, ok := result["NotField"]; ok { + t.Fatal("NotField should not exist") + } + if result["IntData"] != 1 { + t.Fatal("IntData should equal to 1") + } + if result["Int64Data"] != int64(2) { + t.Fatal("Int64Data should equal to int64 2") + } + if result["StrData"] != "world" { + t.Fatal("StrData should equal to world") + } + + jsonStr = "" + result, err = Unmarshal2Map([]byte(jsonStr), &kk) + if err == nil { + t.Fatal("Unmarshal2Map should error") + } + jsonStr = "{}" + result, err = Unmarshal2Map([]byte(jsonStr), &kk) + if err != nil { + t.Fatal("Unmarshal2Map error") + } +} + func unmarshStr(t *testing.T, jsonStr string, obj interface{}) { err := UnmarshalUseNumber([]byte(jsonStr), obj)