Can i have a user defined value as a data type in json in golang

huangapple go评论76阅读模式
英文:

Can i have a user defined value as a data type in json in golang

问题

在Golang中,你可以创建一个类似以下结构的JSON响应:

{
  "Country": "abc"
}

你可以使用以下代码来实现:

type xAxis struct {
  Country string `json:"Country"`
}

func main() {
  data := xAxis{
    Country: "abc",
  }

  jsonData, err := json.Marshal(data)
  if err != nil {
    fmt.Println("Error:", err)
    return
  }

  fmt.Println(string(jsonData))
}

这样,你就可以生成一个符合你要求的JSON响应。

英文:

I am creating a json response in golang.I have a question that i am able to generate a json such as :

{
  "Name" : "Country",
  "Value" : "abc"
}

The value of name and value can change based on the user and the struct I am using is like:

type xAxis struct {
  Name string,
  Value string
}

I want my json to look like this:

{
   "Country" : "abc"
}

Is it possible to create the json like this?

答案1

得分: 3

你可以通过编写自定义的MarshalJSON函数来覆盖Go的json包对结构体进行编组的方式:

type xAxis struct {
    Name  string
    Value string
}

func (a xAxis) MarshalJSON() ([]byte, error) {
    return json.Marshal(map[string]interface{}{a.Name: a.Value})
}

你可以在这里尝试:http://play.golang.org/p/G_E4IpNYIz

英文:

you can override the way Go's json package marshals a struct by writing a custom MarshalJSON function:

type xAxis struct {
	Name  string
	Value string
}

func (a xAxis) MarshalJSON() ([]byte, error) {
	return json.Marshal(map[string]interface{}{a.Name: a.Value})
}

to try it: http://play.golang.org/p/G_E4IpNYIz

答案2

得分: 0

encoding/json包允许你使用map而不是struct。

这可能不如结构体高效,但它是可行的。

data := map[string]string {
    "Country": "abc",
    "Foo": "bar",
}

// 从map创建JSON
j, err := json.Marshal(data)
if err != nil {
    log.Fatal(err)
}
fmt.Println(string(j))
// ==> {"Country":"abc","Foo":"bar"}

// 从JSON创建map
var data2 map[string]string
err = json.Unmarshal(j, &data2)
if err != nil {
    log.Fatal(err)
}
fmt.Println(data2)
// ==> map[Country:abc Foo:bar]

以上是代码的翻译部分。

英文:

The encoding/json package allows you to use a map instead of a struct.

That's probably not as performant as structures, but it works.

data := map[string]string {
	"Country": "abc",
	"Foo": "bar",
}

// Creating JSON from a map
j, err := json.Marshal(data)
if err != nil {
	log.Fatal(err)
}
fmt.Println(string(j))
// ==> {"Country":"abc","Foo":"bar"}

// Creating map from JSON
var data2 map[string]string
err = json.Unmarshal(j, &data2)
if err != nil {
	log.Fatal(err)
}
fmt.Println(data2)
// ==> map[Country:abc Foo:bar]

huangapple
  • 本文由 发表于 2015年1月5日 17:59:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/27777092.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定