2016-07-29 62 views
0

我用网址发送JSON数据与网/ HTTP包,我想有回报一些小写键,但它不工作。Golang返回小写JSON关键

在这个问题的例子,我想小写“计数”和“数据”键。

package main 

import (
    "encoding/json" 
    "fmt" 
    "net/http" 
) 

type tableau struct { 
    Count int  `json"count"` 
    Data []People `json"data"` 
} 

type People struct { 
    Id int `json"Id"` 
    Name string `json"Name"` 
    Age int `json"Age"` 
} 

func main() { 
    http.HandleFunc("/people", recupPeople) 
    fs := http.FileServer(http.Dir("Static")) 
    http.Handle("/", fs) 
    http.ListenAndServe(":80", nil) 
} 

func recupPeople(w http.ResponseWriter, r *http.Request) { 
    listPeople := &tableau{ 
     Count: 4, 
     Data: []People{ 
      People{Id: 1, Name: "Laurent", Age: 20}, 
      People{Id: 2, Name: "Laurent", Age: 20}, 
     }, 
    } 
    peop, _ := json.Marshal(listPeople) 
    fmt.Println(string(peop)) 
    w.Write(peop) 
    json.NewEncoder(w).Encode(listPeople) 
} 

但是,当我检查URL我没有小写。 enter image description here

亲切, 洛朗

+2

你的标签是畸形的:'\'JSON: “计数” \'' – JimB

回答

6

您在标签声明忘记冒号。由于标签格式不正确,字段名称在您的json中。

试试这个:

type tableau struct { 
    Count int  `json:"count"` 
    Data []People `json:"data"` 
} 
+1

只是一个音符:由于Json事情没有正确完成,编码器抓住了字段名称。 –

+1

这是更好的:感谢的很多 –

3

尝试添加:到你的结构标签:

type tableau struct { 
    Count int  `json:"count"` 
    Data []People `json:"data"` 
}