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

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

How to unmarshal an Array of strings inside a struct?

问题

  1. package main
  2. import (
  3. "fmt"
  4. "encoding/json"
  5. )
  6. type sample struct{
  7. field []string `json:"field"`
  8. }
  9. func main() {
  10. dummy:=sample{
  11. field: []string{"color1","color2"},
  12. }
  13. text,_:=json.Marshal(dummy)
  14. fmt.Println(text)
  15. var dummy2 sample
  16. json.Unmarshal(text,&dummy2)
  17. fmt.Println(dummy2)
  18. }

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

英文:
  1. package main
  2. import (
  3. "fmt"
  4. "encoding/json"
  5. )
  6. type sample struct{
  7. field []string `json:"field"`
  8. }
  9. func main() {
  10. dummy:=sample{
  11. field: []string{"color1","color2"},
  12. }
  13. text,_:=json.Marshal(dummy)
  14. fmt.Println(text)
  15. var dummy2 sample
  16. json.Unmarshal(text,&dummy2)
  17. fmt.Println(dummy2)
  18. }

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

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. )
  6. type sample struct {
  7. Field []string `json:"field"`
  8. }
  9. func main() {
  10. dummy := sample{
  11. Field: []string{"color1", "color2"},
  12. }
  13. text, _ := json.Marshal(dummy)
  14. fmt.Println(string(text))
  15. var dummy2 sample
  16. json.Unmarshal(text, &dummy2)
  17. fmt.Println(dummy2)
  18. }

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

输出:

  1. {"field":["color1","color2"]}
  2. {[color1 color2]}
英文:
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. )
  6. type sample struct {
  7. Field []string `json:"field"`
  8. }
  9. func main() {
  10. dummy := sample{
  11. Field: []string{"color1", "color2"},
  12. }
  13. text, _ := json.Marshal(dummy)
  14. fmt.Println(string(text))
  15. var dummy2 sample
  16. json.Unmarshal(text, &dummy2)
  17. fmt.Println(dummy2)
  18. }

Export fields using the first letter capital

Output:

  1. {"field":["color1","color2"]}
  2. {[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:

确定