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条)

报告相同问题?

悬赏问题

  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题