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

报告相同问题?

悬赏问题

  • ¥15 自己做的代码上传图片时,报错
  • ¥15 Lingo线性规划模型怎么搭建
  • ¥15 关于#python#的问题,请各位专家解答!区间型正向化
  • ¥15 unity从3D升级到urp管线,打包ab包后,材质全部变紫色
  • ¥50 comsol温度场仿真无法模拟微米级激光光斑
  • ¥15 上传图片时提交的存储类型
  • ¥15 VB.NET如何绘制倾斜的椭圆
  • ¥15 arbotix没有/cmd_vel话题
  • ¥15 odoo17的分包重新供应路线如何设置?可从销售订单中实时直接触发采购订单或相关单据
  • ¥15 用C语言怎么判断字符串的输入是否符合设定?