将字符串映射到json对象的多种类型? [英] Mapping strings to multiple types for json objects?

查看:316
本文介绍了将字符串映射到json对象的多种类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个可以转换成json对象的映射,如

  {
a :apple,
b:2
}

但golang指定映射是用类型声明的,所以我可以使用map [string] string或map [string] int。如何创建一个像上面这样的json对象?



注意:直到运行时或需要创建时,我都不会知道需要什么数据和/或类型json对象。因此,我不能只创建一个对象,例如:

pre $ type $ Foo struct {
一个字符串`json:a `
B int`json:b`
}


解决方案

您可以随时使用界面{} 来存储任何类型。正如 encoding / json 包中的文档所述:


将JSON解组为一个接口值,Unmarshal将JSON解组为包含在接口值中的具体值。如果接口值为零,即没有存储在其中的具体值,则Unmarshal将其中的一个存储在接口值中:

bool,用于JSON布尔值>
float64,用于JSON数字

字符串,用于JSON字符串

[] interface {},用于JSON数组

$ b $ map [string] interface {},用于JSON对象

无用于JSON null


只需执行以下操作:

  m:= map [string] interface {} {a:apple,b:2} 


I want to create a map that I can transform into a json object such as

{
   "a": "apple",
   "b": 2
}

but golang specifies that the map be declare with types, so I can have map[string]string or map[string]int. How do I create a json object like the above?

Note: I won't know what data and/or types I need until runtime or when I need to create the json object. Therefore I can't just create an object like

type Foo struct {
    A string `json:"a"`
    B int `json:"b"`
}

解决方案

You can always use interface{}to store any type. As the documentation in the encoding/json package says:

To unmarshal JSON into an interface value, Unmarshal unmarshals the JSON into the concrete value contained in the interface value. If the interface value is nil, that is, has no concrete value stored in it, Unmarshal stores one of these in the interface value:

bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null

Just do the following:

m := map[string]interface{}{"a":"apple", "b":2}

这篇关于将字符串映射到json对象的多种类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆