美文网首页
操作Json技巧

操作Json技巧

作者: kker | 来源:发表于2017-06-23 22:56 被阅读87次

忽略某个字段

package main

import (
    "encoding/json"
    "fmt"
)

type User struct{
    Email string `json;"email"`
    Password string `json:"password"`
}

func main() {
    user := User{"email", "1"}
    a,_ := json.Marshal(struct{
        *User
        Password bool `json:"password,omitempty"`
    }{
        User: &user,
    })
    fmt.Println(string(a))
}

添加额外的字段

json.Marshal(struct {
    *User
    Token    string `json:"token"`
    Password bool `json:"password,omitempty"`
}{
    User: user,
    Token: token,
})

合并两个结构体

type BlogPost struct {
    URL   string `json:"url"`
    Title string `json:"title"`
}

type Analytics struct {
    Visitors  int `json:"visitors"`
    PageViews int `json:"page_views"`
}

json.Marshal(struct{
    *BlogPost
    *Analytics
}{post, analytics})

将字符串解析到两个结构体中

json.Unmarshal([]byte(`{
  "url": "attila@attilaolah.eu",
  "title": "Attila's Blog",
  "visitors": 6,
  "page_views": 14
}`), &struct {
  *BlogPost
  *Analytics
}{&post, &analytics})

重命名字段

type CacheItem struct {
    Key    string `json:"key"`
    MaxAge int    `json:"cacheAge"`
    Value  Value  `json:"cacheValue"`
}

json.Marshal(struct{
    *CacheItem

    // Omit bad keys
    OmitMaxAge omit `json:"cacheAge,omitempty"`
    OmitValue  omit `json:"cacheValue,omitempty"`

    // Add nice keys
    MaxAge int    `json:"max_age"`
    Value  *Value `json:"value"`
}{
    CacheItem: item,

    // Set the int by value:
    MaxAge: item.MaxAge,

    // Set the nested struct by reference, avoid making a copy:
    Value: &item.Value,
})

将字段序列化为字符串

type TestObject struct {
    Field1 int    `json:",string"`
}

相关文章

网友评论

      本文标题:操作Json技巧

      本文链接:https://www.haomeiwen.com/subject/jvrhcxtx.html