Unmarshal to struct with slice returns null value instead of empty slice

杀马特。学长 韩版系。学妹 提交于 2020-07-23 08:09:18

问题


If I create a "photo" without any tags it is stored in dynamodb as

"tags": {
   "NULL": true
}, 

But when I query and unmarshal the record I would expect that it converts this into an empty slice instead I get this:

[{"photo_id":"bmpuh3jg","tags":null}]

Is it possible to have it convert it into an empty slice instead? e.g.

[{"photo_id":"bmpuh3jg","tags":[]}]

CODE EXAMPLE

My struct

type Photo struct {
    Id        string   `json:"photo_id"`
    Tags      []string `json:"tags"`
}

Query

photo := &Photo{}
input := &dynamodb.QueryInput{
    TableName:                 aws.String("local.photos"),
    KeyConditionExpression:    aws.String("photo_id = :photo_id"),
    ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
        ":photo_id": {
            S: aws.String(photo_id),
        },
    },
}
db_result, err := db.Query(input)
if err != nil {
    return nil, err
} else if *db_result.Count == int64(0) {
    // No item found
    return nil, err
}

err = dynamodbattribute.UnmarshalListOfMaps(db_result.Items, photo)
if err != nil {
    return nil, err
}

photoJSON, err := json.Marshal(photo)
if err != nil {
    return nil, err
}

return photoJSON, nil

回答1:


If I understand your question correctly, to achieve a result with an empty slice for Tags ({"photo_id":"bmpuh3jg","tags":[]}), you can do it like this:

  jsonString := `{"photo_id":"bmpuh3jg","tags":null}`

  photo := &Photo{}
  err := json.Unmarshal([]byte(jsonString), &photo)
  if err != nil {
     fmt.Println(err.Error())
  }

  // Here is a trick. Replace nil with an empty slice.
  if photo.Tags == nil {
    photo.Tags = []string{}
  }
  elemJSON, err := json.Marshal(photo)
  if err != nil {
    fmt.Println(err.Error())
  }
  fmt.Println(string(elemJSON)) //{"photo_id":"bmpuh3jg","tags":[]} 

To understand, why a nil slice encodes as the null JSON, you can check official documentation https://golang.org/pkg/encoding/json/

Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON value.

Check on Go Playground: https://play.golang.org/p/BsxTpBlypV5



来源:https://stackoverflow.com/questions/58569272/unmarshal-to-struct-with-slice-returns-null-value-instead-of-empty-slice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!