2017-10-10 04:07
浏览 282


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 (

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

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

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

    a := &struct {
        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 {

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

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

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

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

func main() {



(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条回答 默认 最新

相关推荐 更多相似问题