如何在结构体中解组字符串数组?

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

How to unmarshal an Array of strings inside a struct?

问题

package main
import (
    "fmt"
     "encoding/json"
)    
type sample struct{
    field []string `json:"field"`
}
func main() {
  dummy:=sample{
      field: []string{"color1","color2"},
  }
  text,_:=json.Marshal(dummy)
  fmt.Println(text)
  var dummy2 sample
  json.Unmarshal(text,&dummy2)
  fmt.Println(dummy2)
}

在这段代码中,我试图将类型为sample的变量dummy进行编组,但是我得到了一些奇怪的字符串值,当我对该字符串进行解组时,我得到了一个空的结构体。请问正确的做法是什么?

英文:
package main
import (
    "fmt"
     "encoding/json"
)    
type sample struct{
    field []string `json:"field"`
}
func main() {
  dummy:=sample{
      field: []string{"color1","color2"},
  }
  text,_:=json.Marshal(dummy)
  fmt.Println(text)
  var dummy2 sample
  json.Unmarshal(text,&dummy2)
  fmt.Println(dummy2)
}

In this code am trying to marshal the variable dummy of type struct but I am receiving some odd values in string and when I unmarshal that string I receive an empty struct.What will be the correct way to do this?

In this code am trying to marshal the variable dummy of type struct but I am receiving some odd values in string and when I unmarshal that string I receive an empty struct.What will be the correct way to do this?

答案1

得分: 0

package main

import (
	"encoding/json"
	"fmt"
)

type sample struct {
	Field []string `json:"field"`
}

func main() {
	dummy := sample{
		Field: []string{"color1", "color2"},
	}
	text, _ := json.Marshal(dummy)
	fmt.Println(string(text))

	var dummy2 sample
	json.Unmarshal(text, &dummy2)
	fmt.Println(dummy2)
}

将字段的首字母大写以导出

输出:

{"field":["color1","color2"]}
{[color1 color2]}
英文:
package main

import (
	"encoding/json"
	"fmt"
)

type sample struct {
	Field []string `json:"field"`
}

func main() {
	dummy := sample{
		Field: []string{"color1", "color2"},
	}
	text, _ := json.Marshal(dummy)
	fmt.Println(string(text))

	var dummy2 sample
	json.Unmarshal(text, &dummy2)
	fmt.Println(dummy2)
}

Export fields using the first letter capital

Output:

{"field":["color1","color2"]}
{[color1 color2]}

huangapple
  • 本文由 发表于 2023年5月25日 12:21:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76328923.html
匿名

发表评论

匿名网友

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

确定