2016-07-29 21 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"` 
}