Last active
October 19, 2016 05:05
-
-
Save yangyuqian/afa596105720d9165a12480f00fbfd83 to your computer and use it in GitHub Desktop.
Go处理输入输出格式不一致的场景
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
) | |
/* | |
处理JSON的输入和输出格式不一致的情况下, | |
用同一个struct定义的场景 | |
*/ | |
type A struct { | |
ID int `json:"id"` | |
Name string `json:"name"` | |
Age int `json:"age"` | |
} | |
type aAlias A | |
// 构造一个临时对象,可以覆盖一些A里面的定义,用组合出来的新对象 | |
// 来构造json结果 | |
func (a *A) MarshalJSON() ([]byte, error) { | |
return json.Marshal(struct { | |
Name string `json:"name1"` | |
*aAlias | |
}{ | |
Name: fmt.Sprintf("B: %s", a.Name), | |
aAlias: (*aAlias)(a), | |
}) | |
} | |
// 构造一个临时对象,先把json数据解析出来,然后对原对象进行赋值 | |
func (a *A) UnmarshalJSON(data []byte) error { | |
b := &struct { | |
Name string `json:"x_name"` | |
*aAlias | |
}{ | |
Name: a.Name, | |
aAlias: (*aAlias)(a), | |
} | |
json.Unmarshal(data, b) | |
a.Name = b.Name | |
return nil | |
} | |
func main() { | |
a, _ := json.Marshal(&A{ | |
ID: 1, | |
Name: "jsonA", | |
Age: 18, | |
}) | |
fmt.Println("a.json:", string(a)) | |
content := []byte(`{ | |
"id": 1, | |
"x_name": "x_json_A", | |
"age": 13 | |
}`) | |
aa := &A{} | |
json.Unmarshal(content, aa) | |
fmt.Println("aa.struct:", aa) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment