英文:
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]}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论