MarshalJSON is not called

I am trying to customize the output MarshalJSONusing the interface:

func (m *RawMessage) MarshalJSON() ([]byte, error)

I followed this tutorial: http://choly.ca/post/go-json-marshalling/

My goal is to remove one of the fields with true / false (if set or not), so I wrote this function:

func (u *Edition) MarshalJSON() ([]byte, error) {
    var vaultValue bool
    vaultValue = true
    var onlineValue bool
    vaultValue = false
    fmt.Println("here")
    if u.Vault == nil {
        vaultValue = false
    }
    if u.Online == nil {
        onlineValue = false
    }
    type AliasEdition Edition
    return json.Marshal(&struct {
        Vault  bool `json:"vault,omitempty"`
        Online bool `json:"online,omitempty"`
        *AliasEdition
    }{
        Vault:        vaultValue,
        Online:       onlineValue,
        AliasEdition: (*Alias)(u),
    })
}

JSON is created from the map with the following statement:

json.NewEncoder(w).Encode(EditionsMap)

Obviously, this EditionsMapis a map of structures Edition:

var EditionsMap map[string]datamodel.Edition

The problem is that the function MarshalJSONapparently never gets called.

Maybe I'm doing something wrong, but I don’t understand what the problem is, I understand that I just need to implement this function to call it.

+4
source share
1

, Edition.MarshalJSON() :

func (u *Edition) MarshalJSON() ([]byte, error)

( datamodel.Edition):

var EditionsMap map[string]datamodel.Edition
// ...
json.NewEncoder(w).Encode(EditionsMap)

. datamodel.Edition MarshalJSON().

Spec: :

. . T , T. *T - , *T T ( T).

, , :

var EditionsMap map[string]*datamodel.Edition
// ...
if err := json.NewEncoder(w).Encode(EditionsMap); err != nil {
    panic(err) // HANDLE error somehow, do not omit it like in your example!
}

*Edition MarshalJSON(), json. Go Playground.

Edition.MarshalJSON() :

func (u Edition) MarshalJSON() ([]byte, error)

, , Edition, *Edition. Go Playground.

+9

Source: https://habr.com/ru/post/1652591/


All Articles