在Go中解组通用json [英] unmarshal generic json in Go
问题描述
我是一名新的Go程序员(来自Java),我想重现一种通用的方法,该方法很容易在Java中使用.
I'm a new Go programmer (From Java) and I would like to reproduce a generic way which is esay to use in Java.
我想创建一些函数,使我可以对JSON字符串进行解组,以避免代码重复.
I want to create some function which allow me to do an Unmarshal on a JSON string in order to avoid code duplicity.
这是我当前的无效代码:
This is my current code which is not working :
type myStruct1 struct {
id string
name string
}
func (obj myStruct1) toString() string {
var result bytes.Buffer
result.WriteString("id : ")
result.WriteString(obj.id)
result.WriteString("\n")
result.WriteString("name : ")
result.WriteString(obj.name)
return result.String()
}
func main() {
content := `{id:"id1",name="myName"}`
object := myStruct1{}
parseJSON(content, object)
fmt.Println(object.toString())
}
func parseJSON(content string, object interface{}) {
var parsed interface{}
json.Unmarshal([]byte(content), &parsed)
}
此代码在运行时会向我返回此:
This code, on run, returns me this :
id :
name :
你有什么主意吗?
谢谢
推荐答案
问题是您要写入通用类型吗?您可能想要一个字符串映射.无论如何,这都可以与BSON一起使用:
The issue is you want to write to a generic type? You probably want a string map. This works with BSON anyways:
var anyJson map[string]interface{}
json.Unmarshal(bytes, &anyJson)
您将能够像这样访问字段:
You'll be able to access the fields like so:
anyJson["id"].(string)
别忘了输入断言您的值,并且它们必须是正确的类型,否则会出现恐慌. (您可以在golang网站上了解有关类型断言的更多信息)
Don't forget to type assert your values, and they must be the correct type or they'll panic. (You can read more about type assertions on the golang site)
这篇关于在Go中解组通用json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!