简体   繁体   English

如何确保首先解析根结构的文件,然后解析嵌入式结构的字段

[英]How do I make sure that the fileds of the root struct get parsed first and then the fields of embedded struct gets parsed

I have the struct as follows:- 我的结构如下:

type Inner struct {
    FooInner string `json:"fooInner"`
    BarInner string `json:"barInner,omitempty"`
}

type Root struct {
    Inner
    Foo string `json:"foo"`
    Bar string `json:"bar"`
}

I want the fields of "Root" struct to be parsed first and then the fields of the "Inner" struct. 我希望先解析“ Root”结构的字段,然后再解析“ Inner”结构的字段。 But here the fields of Inner struct is getting parsed first. 但是,这里先解析Inner struct的字段。

If you are asking about JSON marshaling (which is not parsing) and want fields marshaled in a certain order, a marshaler will typically marshal fields in their index order & recurse any embedded structs along the way. 如果您询问有关JSON封送处理(不解析)的信息,并希望按特定顺序封送字段,则封送处理程序通常会按索引顺序封送字段,并递归沿途的所有嵌入式结构。 Struct field indices - as seen by the reflect package that json.Marhsal uses - are defined by their order of appearance in your code. 结构字段索引-如json.Marhsal使用的reflectjson.Marhsal -由它们在代码中的出现顺序定义。

So put the fields you want first - and any embedded structs later: 因此,请首先放置所需字段,然后再放置任何嵌入式结构:

type Root struct {
    Foo string `json:"foo"`
    Bar string `json:"bar"`
    Inner // <- move this last
}

Playground Example 操场上的例子

b, _ := json.Marshal(Root{})

{"foo":"","bar":"","fooInner":""}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM