登录
首页 >  Golang >  Go问答

如果 json 字节字段与特定类型匹配,如何仅将其解组到字段中?

来源:stackoverflow

时间:2024-04-14 15:00:36 253浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《如果 json 字节字段与特定类型匹配,如何仅将其解组到字段中?》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

我想做的事被评论了:

type foo struct {
  Message string `json:"message"`
}

func bar() {
  //The "message" field contains a bool type which does not 
  //match the equivalent "message" field in foo, a string type
  jsonData := byte[]("{
    \"message\": true
  }")
  var baz foo
  //Because the type of "message" in the json bytes is 
  //bool and not a string, put "" inside baz.Message
  json.Unmarshal(jsonData, &baz) 
}

如何解组 json 字节数组,然后仅在该字段与 json 字节数组字段中的类型匹配时填充特定字段?如果字段类型与 json 字节数组字段类型不匹配,则放入 nil、"" 等占位符值?


解决方案


有很多方法可以处理这个问题,只要您拨打 fix your question to something that can be answered。我喜欢的方法是将其解组为 interface{} 类型的变量,然后您可以检查该变量:

package main

import (
    "encoding/json"
    "fmt"
)

type foo struct {
    Message interface{} `json:"message"`
}

func bar() {
    //The "message" field contains a bool type which does not
    //match the equivalent "message" field in foo, a string type
    jsonData := []byte(`{
    "message": true
  }`)
    var baz foo
    //Because the type of "message" in the json bytes is
    //bool and not a string, put "" inside baz.Message
    err := json.Unmarshal(jsonData, &baz)
    fmt.Printf("unmarhal error is: %v\n", err)
    if err == nil {
        fmt.Printf("baz.Message is now: %T = %v\n", baz.Message, baz.Message)
    }
}

func main() {
    bar()
}

(Go Playground link)

现在应该相当清楚如何打开类型(解码后)并查看您得到的是否是您想要的。如果是这样,请使用它。如果没有,请使用您的默认值。如果有必要,首先将传入的 json 解码为更通用的 go 类型,然后填写您真正想要处理的特定类型。

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>