如何在匿名嵌套结构中使用json标签?

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

How to use json tags in anonymously nested struct?

问题

我有以下匿名结构体:

func wrapHal(selfHref string) interface{} {
	return struct {
		Links struct `json:"_links"`{
			Self struct {
				Href string
			}
		}
	}{
		Links: struct {
			Self struct {
				Href string
			}
		}{
			Self: struct {
				Href string
			}{
				Href: selfHref,
			},
		},
	}
}

我想知道在使用json.Marshal将其序列化为JSON时,是否可以将Links重命名为_links

是否可能?如果是,如何实现?

英文:

I have the following anonymous struct

func wrapHal(selfHref string) interface{} {
	return struct {
		Links struct `json: "_links"`{ # does not work, returns error "expected expression"
			Self struct {
				Href string
			}
		}
	}{
		Links: struct {
			Self struct {
				Href string
			}
		}{
			Self: struct {
				Href string
			}{
				Href: selfHref,
			},
		},
	}
}

I want to know if it is possible to rename from Links to _links when I serialize to JSON using json.Marshal

Is it possible? If so, how?

答案1

得分: 1

问题出在基本结构上。

	type s struct {
		Links struct {
			Self struct {
				Href string
			}
		} `json:"_links"`
	}

这是正确的语法。

英文:

The issue is with the base structure.

	type s struct {
		Links struct {
			Self struct {
				Href string
			}
		} `json:"_links"`
	}

is the correct syntax

huangapple
  • 本文由 发表于 2022年7月23日 05:14:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/73086139.html
匿名

发表评论

匿名网友

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

确定