2017-11-01 1 views
-1

私はjsonが構造体をエンコードする私のサーバーで非常に単純なhttpの共鳴を持っています。しかし、それはちょうど空白を送信する{}JSONエンコード空白を返すGolang

私はそれが間違っているかどうかは分かりませんが、私はエラーが表示されません。これは私のJSONエンコードです:データを終わらrecievingで

// Set uuid as string to user struct 
    user := User{uuid: uuid.String()} 
    fmt.Println(user) // check it has the uuid 

    responseWriter.Header().Set("Content-Type", "application/json") 
    responseWriter.WriteHeader(http.StatusCreated) 

    json.NewEncoder(responseWriter).Encode(user) 

あります

Content-Type application/json 
Content-Length 3 
STATUS HTTP/1.1 201 Created 
{} 

は、なぜそれが私のUUIDデータを与えるものではありませんか?エンコーディングに何か問題がありますか?

+6

エクスポートするフィールド名

はこれを試してみてください。重複している可能性のあるhttps://stackoverflow.com/questions/26327391/go-json-marshalstruct-returnsを参照してください。 –

+0

それがうまくいくか試してみてください。 – Sir

+3

[json.Marshal(構造体)が "{}"を返す可能性があります(https://stackoverflow.com/questions/26327391/go-json-marshalstruct-returns) – tgogos

答えて

2

フィールド名をthe first character of the identifier's name a Unicode upper case letter (Unicode class "Lu")にエクスポートします。

package main 

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

type User struct { 
    Uuid string 
} 

func handler(responseWriter http.ResponseWriter, r *http.Request) { 
    user := User{Uuid: "id1234657..."} // Set uuid as string to user struct 
    fmt.Println(user)     // check it has the uuid 
    responseWriter.Header().Set("Content-Type", "application/json") 
    responseWriter.WriteHeader(http.StatusCreated) 
    json.NewEncoder(responseWriter).Encode(user) 
} 

func main() { 
    http.HandleFunc("/", handler)   // set router 
    err := http.ListenAndServe(":9090", nil) // set listen port 
    if err != nil { 
     log.Fatal("ListenAndServe: ", err) 
    } 
} 

出力(http://localhost:9090/):

{"Uuid":"id1234657..."} 
+0

ああ、そのような簡単な解決策!大文字はそれを解決しました:)ありがとう – Sir

+0

あなたは大歓迎です。 –

関連する問題