duanpin2034 2017-10-10 04:07
浏览 282
已采纳

如何将我的自定义UnmarshalJSON方法应用于嵌入式结构?

So, I have struct P. I need to unmarshal some json data into P but sometimes it comes embedded struct, Embedded. In either case, I unmarshal the json from the API and need to format the "Formatted" field. It seems in the Embedded case my unmarshaller doesn't get called.

I have the following code:

package main

import (
    "encoding/json"
    "fmt"
)

type P struct {
    Name      string `json:"name"`
    Formatted string `json:"formatted"`
}

type Embedded struct {
    A struct {
        B struct {
            *P
        } `json:"b"`
    } `json:"a"`
}

func (p *P) UnmarshalJSON(b []byte) error {
    type Alias P

    a := &struct {
        *Alias
    }{
        Alias: (*Alias)(p),
    }

    if err := json.Unmarshal(b, &a); err != nil {
        return err
    }

    a.Formatted = fmt.Sprintf("Hi, my name is %v", a.Name)

    return nil
}

func simple() {
    b := []byte(`{"name":"bob"}`)

    p := &P{}
    if err := json.Unmarshal(b, &p); err != nil {
        panic(err)
    }

    fmt.Printf("normal: %+v
", p)
}

func embedded() {
    b := []byte(`{"a":{"b":{"name":"bob"}}}`)

    e := &Embedded{}
    if err := json.Unmarshal(b, &e); err != nil {
        panic(err)
    }

    fmt.Printf("embedded: %+v
", e.A.B.P)
}

func main() {
    simple()

    embedded()

}

(I realize I can get rid of the custom unmarshaller and create a method to format the name but wanted to see if this way was possible.)

  • 写回答

2条回答 默认 最新

  • dtgv52982 2017-10-10 06:09
    关注

    I don't know enough to explain all the reasons, I will just list what works and what doesn't. Someone more knowledgeable can fill you in on the reasons behind it.

    The following works when B is a *struct, not sure why.

    type Embedded struct {
        A struct {
            B *struct {
                P
            } `json:"b"`
        } `json:"a"`
    }
    

    The following also works. I'm guessing that using an anonymous struct had some effect in the last one since a *struct is not required here.

    type embedP struct {
                P
    }
    
    type Embedded struct {
        A struct {
            B embedP `json:"b"`
        } `json:"a"`
    }
    

    The following works if *P is initialised.

    type embedP struct {
                *P
    }
    
    type intermediate struct {
            B embedP `json:"b"`
    }
    
    type Embedded struct {
        A  intermediate `json:"a"`
    }
    
    e := &Embedded{A:intermediate{embedP{P:&P{}}}}
    

    But the same thing doesn't work with anonymous structs.

    type Embedded struct {
        A struct {
            B struct {
                *P
            } `json:"b"`
        } `json:"a"`
    }
    
    e := &Embedded{A : struct{B struct{*P}`json:"b"`}{B: struct{*P}{&P{}}}}
    

    Play link

    Other improvements

    If p := &P{} is already a pointer you don't need to pass &p in json.Unmarshal. json.Unmarshal(b, p) would suffice. Same with e := &Embedded{}.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接
  • ¥15 MATLAB中使用parfor,矩阵Removal的有效索引在parfor循环中受限制
  • ¥20 Win 10 LTSC 1809版本如何无损提升到20H1版本
  • ¥50 win10 LTSC 虚拟键盘不弹出
  • ¥30 微信小程序请求失败,网页能正常带锁访问
  • ¥15 Matlab求解微分方程,如何用fish2d进行预优?