2017-07-25 51 views
4

可以說,我有以下的JSON如何從golang中解析json的非標準時間格式?

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

,我想它解碼成以下結構

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

這樣

person := Person{} 

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

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

它給我的錯誤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/ 44705817/parsing-a-json-date-in-revel) – RickyA

+1

[在golang中解析日期字符串]可能的副本(https://stackoverflow.com/questions/25845172/parsing-date-string-in-golang) – Adrian

回答

4

這是您需要實現自定義編組和解組函數的情況。

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

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

通過以下json package的Golang文檔中的例子中,你得到的東西,如:

// 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

Right ,對於'UnmarshalJSON'函數,OP可以根據需要支持的不同格式添加多個'time.Parse'嘗試。我相信'time.RFC3339'的格式是默認的解析器,更多的格式可以在[docs](https://golang.org/pkg/time/#pkg-constants) – Jonathan

+1

找到。當然,當你有自定義聯合國/主管職能,你應該儘量涵蓋每一個可能的情況。 – Kiril

+0

Minor nit:根據[code style](https://github.com/golang/go/wiki/CodeReviewComments#initialisms),它應該是'JSONBirthDate',而不是'JsonBirthDate'。 –