英文:
struct not been entirely marshaled
问题
我有一个结构体需要进行编组以便消费Web服务,但在我的测试中,Marshal函数只对一个字段进行编码:
type DataRows []struct {
mData interface{}
}
type DataColumns []struct {
mColumnName string
mColumnType int
mColumnPrecision int
mColumnScale int
}
type DataTables []struct {
mDataColumns DataColumns
mDataRows DataRows
mIndex int
}
type CFFDataSet struct {
mDataTables DataTables
mUser string
DBServer int
}
func main() {
ds := CFFDataSet{
mDataTables: DataTables{{
mDataColumns: DataColumns{{
mColumnName: "Test",
mColumnType: 1,
mColumnPrecision: 1,
mColumnScale: 1,
}},
mDataRows: DataRows{{
mData: "Test",
}},
mIndex: 0,
}},
mUser: "Teste",
DBServer: 2,
}
marshaled, _ := json.Marshal(ds)
fmt.Println(string(marshaled))
}
返回的结果是:
{"DBServer":2}
有人能给我一个提示,为什么不起作用吗?
<details>
<summary>英文:</summary>
I have a struct what I need to marshal to consume the webservice, but in my tests I the Marshal function only encode one field:
type DataRows []struct {
mData interface{}
}
type DataColumns []struct {
mColumnName string
mColumnType int
mColumnPrecision int
mColumnScale int
}
type DataTables []struct {
mDataColumns DataColumns
mDataRows DataRows
mIndex int
}
type CFFDataSet struct {
mDataTables DataTables
mUser string
DBServer int
}
func main() {
ds := CFFDataSet{
mDataTables: DataTables{{
mDataColumns: DataColumns{{
mColumnName: "Test",
mColumnType: 1,
mColumnPrecision: 1,
mColumnScale: 1,
}},
mDataRows: DataRows{{
mData: "Test",
}},
mIndex: 0,
}},
mUser: "Teste",
DBServer: 2,
}
marchaled, _ := json.Marshal(ds)
fmt.Println(string(marchaled))
}
is returning
$ go run getrest.go
{"DBServer":2}
Can someone give me a hint why not this working ?
</details>
# 答案1
**得分**: 1
你的其他字段都是未导出的(类似于其他语言中的私有字段),无法被解码器访问。这是由字段名的首字母大小写决定的,需要大写。
以下是一个示例,使用与 JSON 字段名不同的结构体字段名:
```go
var jsonBlob = []byte(`[
{"Name": "Platypus", "Purchase": "Monotremata"},
{"Name": "Quoll", "Purchase": "Dasyuromorphia"}
]`)
type Animal struct {
Name string
Order string `json:"Purchase"`
}
var animals []Animal
err := json.Unmarshal(jsonBlob, &animals)
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("%+v", animals)
链接:https://play.golang.org/p/iJqaXQY7Ch
英文:
All your other fields are unexported (like private in other languages) and the unmarshaller can't access them. This is designated by the case of the first letter in the field name, needs to be uppercase.
For reference, here's an example using a field name on your struct that differs from the json's field name;
var jsonBlob = []byte(`[
{"Name": "Platypus", "Purchase": "Monotremata"},
{"Name": "Quoll", "Purchase": "Dasyuromorphia"}
]`)
type Animal struct {
Name string
Order string `json:"Purchase"`
}
var animals []Animal
err := json.Unmarshal(jsonBlob, &animals)
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("%+v", animals)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论