php property_exists json,json · PHP/Python/前端/Linux 等等 学习笔记 · 看云

[TOC]

## 标识符

### omitempty 为空不显示

添加`omitempty`后,如果 data 为空,则不显示 data

如 0 ,"",flase 等都为空值

```

type H struct{

Msg string `json:"msg"`

Data interface{} `json:"data,omitempty"`

}

```

`{"name":"asd"}`

### - 过滤都该字段的序列化

```

type H struct{

Msg string `json:"msg"`

Data interface{} `json:"-"`

}

```

`{"name":"asd"}`

### 指定序列化格式,可让 int 转为 string

```

type User struct {

Name string `json:"name"`

Age int8 `json:"age,string"`

}

```

`{"name":"asd","age":"123"}`

## json.Marshal

```

type ColorGroup struct {

ID int

Name string

Colors []string

}

group := ColorGroup{

ID: 1,

Name: "Reds",

Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},

}

b, err := json.Marshal(group)

if err != nil {

fmt.Println("error:", err)

}

fmt.Printf("%+v\n", string(b))

// {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}

```

## json.Unmarshal

```

var jsonBlob = []byte(`[

{"Name": "Platypus", "Order": "Monotremata"},

{"Name": "Quoll", "Order": "Dasyuromorphia"}

]`)

type Animal struct {

Name string

Order string

}

var animals []Animal

err := json.Unmarshal(jsonBlob, &animals)

if err != nil {

fmt.Println("error:", err)

}

fmt.Printf("%+v", animals)

// [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]

```

### json.Indent 缩进json

```

var jsonBlob = []byte(`[

{"Name": "Platypus", "Order": "Monotremata"},

{"Name": "Quoll", "Order": "Dasyuromorphia"}

]`)

var a bytes.Buffer

err := json.Indent(&a, jsonBlob, "", " ")

if err != nil {

panic(err)

}

fmt.Printf("%+v\n", a.String())

/*

[

{

"Name": "Platypus",

"Order": "Monotremata"

},

{

"Name": "Quoll",

"Order": "Dasyuromorphia"

}

]

*/

```

## json.HTMLEscape

```

var out bytes.Buffer

json.HTMLEscape(&out, []byte(`{"Name":"HTML content"}`))

out.WriteTo(os.Stdout)

// Output:

//{"Name":"\u003cb\u003eHTML content\u003c/b\u003e"}

```

## json.NewDecoder 有杂质信息也可序列化

```

type User struct {

UserName string `json:"username"`

Password string `json:"password"`

}

jsonString := `{

"username": "foobar@example.com",

"password": "YOUR PASSWORD"

}otherinfo`

str := strings.NewReader(jsonString) // io.Reader

usr := User{}

err := json.NewDecoder(str).Decode(&usr)

if err != nil {

log.Fatalf("Decode failed, %#v\n", err)

}

log.Printf("User %#v\n", usr)//User main.User{UserName:"foobar@example.com", Password:"YOUR PASSWORD"}

```

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值