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 CATIA有些零件打开直接单机确定终止
  • ¥15 请问有会的吗,用MATLAB做
  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 ARIMA模型时间序列预测用pathon解决
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序,怎么查看客户esp32板子上程序及烧录地址