D
D
Dmitry Sviridov2020-09-30 21:06:46
go
Dmitry Sviridov, 2020-09-30 21:06:46

What is the correct way to deserialize JSON into a structure in Go?

The API returns a json object, one of whose fields is a nested object. But if this nested object does not exist, then in the response this field does not contain null, but double brackets (an empty array). That is, as I understand it, these are generally different types (either an array or an object). How can this thing be correctly deserialized into a structure so that the corresponding field of the structure contains either a pointer to an object, if any, or nil?

I tried like this, but it doesn't quite work out, because in Goals it's not nil, but &{nil}. This is because an uninitialized structure is not nil.

type Conversion struct {
  TotalConversions *int                       `json:"total_conversions,omitempty"`
  Goals                     *ConversionBlock `json:"maintrigger,omitempty"` // Это вложенный объект, при отсутствии которого тут []
}

type block struct {
  ID          *int            `json:"id,omitempty"`
  Name     *string      `json:"name,omitempty"`
  Created *DateTime `json:"created,omitempty"`
}

type ConversionBlock struct {
  *block
}

func (d *ConversionBlock) UnmarshalJSON(data []byte) error {
  if string(data) == "[]" {
    *d = ConversionBlock{}
    return nil
  }
  var bl block

  err := json.Unmarshal(data, &bl)
  if err != nil {
    return errors.New("UnmarshalJSON:  " + err.Error())
  }

  *d = ConversionBlock{
    &bl,
  }
  return nil
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Samsonov, 2020-09-30
@dimuska139

I can't check, but it's probably true

if string(data) == "[]" {
    return nil
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question