2017-07-25 8 views
4

は、私は次のようなJSONgolangのjsonから非標準の時刻形式を解析するには?

{ 
    name: "John", 
    birth_date: "1996-10-07" 
} 

を持って言うことができますし、私は次のような構造にそれを解読したい私にエラーを与えるこの

person := Person{} 

decoder := json.NewDecoder(req.Body); 

if err := decoder.Decode(&person); err != nil { 
    log.Println(err) 
} 

よう

type Person struct { 
    Name string `json:"name"` 
    BirthDate time.Time `json:"birth_date"` 
} 

parsing time ""1996-10-07"" as ""2006-01-02T15:04:05Z07:00"": cannot parse """ as "T"

マニュアルを解析する場合LY私はこの

t, err := time.Parse("2006-01-02", "1996-10-07") 

が、時間値は、JSON文字列からあるときにどのように私は上記の形式でそれを解析するためのデコーダを入手できますようにそれを行うだろうか?

+1

([レヴェルでJSONの日時を解析]の可能重複https://stackoverflow.com/questions/:json packageのGolangドキュメントの例に従うことにより

UnmarshalJSON(b []byte) error { ... } MarshalJSON() ([]byte, error) { ... } 

はあなたのような何かを得ます44705817/parsing-a-json-datetime-in-revel) – RickyA

+1

[golangの日付文字列を解析する]の可能な複製(https://stackoverflow.com/questions/25845172/parsing-date-string-in-golang) – Adrian

答えて

4

カスタムマーシャルとアンマーシャリング機能を実装する必要がある場合です。

// first create a type alias 
type JsonBirthDate time.Time 

// Add that to your struct 
type Person struct { 
    Name string `json:"name"` 
    BirthDate JsonBirthDate `json:"birth_date"` 
} 

// imeplement Marshaler und Unmarshalere interface 
func (j *JsonBirthDate) UnmarshalJSON(b []byte) error { 
    s := strings.Trim(string(b), "\"") 
    t, err := time.Parse("2006-01-02", s) 
    if err != nil { 
     return err 
    } 
    *j = JB(t) 
    return nil 
} 

func (j JsonBirthDate) MarshalJSON() ([]byte, error) { 
    return json.Marshal(j) 
} 

// Maybe a Format function for printing your date 
func (j JsonBirthDate) Format(s string) string { 
    t := time.Time(j) 
    return t.Format(s) 
} 
+0

右'UnmarshalJSON'関数の場合、OPはいくつの異なるフォーマットをサポートする必要があるかに基づいて、複数の' time.Parse'試行を追加することができます。私は 'time.RFC3339'の形式はデフォルトのパーサーであり、より多くの形式は[docs](https://golang.org/pkg/time/#pkg-constants) – Jonathan

+1

にあります。カスタムのun/marshal関数を使用する場合は、可能なすべてのケースをカバーするようにしてください。 – Kiril

+0

マイナーニト:[コードスタイル](https://github.com/golang/go/wiki/CodeReviewComments#initialisms)に従って、 'JsonBirthDate'ではなく' JSONBirthDate'でなければなりません。 –

関連する問題