嵌入结构体但只在 JSON 中包含特定字段。

huangapple go评论93阅读模式
英文:

Embed struct but only have certain fields in json

问题

我有一个结构体,我想嵌入它,但只想对该结构体的某些字段进行JSON编码(并将它们转换为小写)。这可能吗?

package main

import (
	"encoding/json"
	"fmt"
	"net/url"
)

type MyStruct struct {
	Name string `json:"name"`
	*url.URL
}

func main() {
	m := &MyStruct{
		"Bob",
		&url.URL{
			Scheme: "http",
		},
	}

	j, err := json.Marshal(m)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(string(j))  // 希望输出 { "name": "Bob", "scheme": "http" }
}

以上是您要翻译的内容。

英文:

I have a struct that I want to embed but want to json encode only certain fields of that struct (and lowercase them). Is that possible?

https://play.golang.org/p/bEC4zlx2oC:

package main

import (
	"encoding/json"
	"fmt"
	"net/url"
)

type MyStruct struct {
	Name string `json:"name"`
	*url.URL
}

func main() {
	m := &MyStruct{
		"Bob",
		&url.URL{
			Scheme: "http", 
		},
	}

	j, err := json.Marshal(m)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(string(j))  // want {"name":"Bob","scheme":"http"}
}

答案1

得分: 3

扩展我的评论并提供示例。

这是可行的,你需要实现Marshal接口。

例如:

func (u *MyStruct) MarshalJSON() ([]byte, error) {
    return json.Marshal(&struct {
        Name   string `json:"name"`
        Scheme string `json:"scheme"`
    }{
        Name:   u.Name,
        Scheme: u.Scheme,
    })
}

Play链接:https://play.golang.org/p/LLchuOdYvf

输出:

{"name":"Bob","scheme":"http"}
英文:

Expanding my comment with example.

It is feasible, you have to implement Marshal interface.

For example:

func (u *MyStruct) MarshalJSON() ([]byte, error) {
	return json.Marshal(&struct {
		Name   string `json:"name"`
		Scheme string `json:"scheme"`
	}{
		Name:   u.Name,
		Scheme: u.Scheme,
	})
}

Play Link: https://play.golang.org/p/LLchuOdYvf

Output:

{"name":"Bob","scheme":"http"}

huangapple
  • 本文由 发表于 2017年7月24日 00:32:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/45267409.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定