我有什么:某种 API 的两个结构
type BaseUser struct {
ID int64 `json:"user_id"`
Name string `json:"user_name"`
Email string `json:"user_email"`
}
和
type UserWithAddress struct {
BaseUser
Postal string `json:"user_postal"`
City string `json:"user_city"`
Street string `json:"user_street"`
}
我想做什么:将json键从snake_case转换为camelCase。可以说,这是一个请求正文
{
"user_id": 123,
"user_name": "test",
"user_email": "test@mail.com",
"user_postal": "12312",
"user_city": "city",
"user_street": "street"
}
因此,经过某种转换,我想要这个输出
{
"userId": 123,
"userName": "test",
"userEmail": "test@mail.com",
"userPostal": "12312",
"userCity": "city",
"userStreet": "street"
}
目前我该如何处理:我用 camelCasejson标签制作了另外两个结构
type BaseUserCamelCase struct {
ID int64 `json:"userId"`
Name string `json:"userName"`
Email string `json:"userEmail"`
}
和
type UserWithAddressCamelCase struct {
BaseUserCamelCase
Postal string `json:"userPostal"`
City string `json:"userCity"`
Street string `json:"userStreet"`
}
我的转变看起来像
var userWithAddressCamelCase UserWithAddressCamelCase
userWithAddressCamelCase.BaseUserCamelCase = BaseUserCamelCase(userWithAddress.BaseUser)
//I can't cast whole userWithAddressCamelCase object to another type because of different field names - BaseUser and BaseUserCamelCase
userWithAddressCamelCase.Name = userWithAddress.Name
userWithAddressCamelCase.Email = userWithAddress.Email
userWithAddressCamelCase.Postal = userWithAddress.Postal
//and so on
而且我不喜欢它,因为如果BaseUser或UserWithAddress将要长大,我必须在%CamelCase结构中添加适当的字段。
我的问题:是否有另一种更有效的方法来处理键转换?
qq_花开花谢_0
汪汪一只猫
相关分类