当前位置: 首页>>代码示例>>Golang>>正文


Golang Time.UnmarshalJSON方法代码示例

本文整理汇总了Golang中Time.Time.UnmarshalJSON方法的典型用法代码示例。如果您正苦于以下问题:Golang Time.UnmarshalJSON方法的具体用法?Golang Time.UnmarshalJSON怎么用?Golang Time.UnmarshalJSON使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Time.Time的用法示例。


在下文中一共展示了Time.UnmarshalJSON方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: UnmarshalJSON

// UnmarshalJSON implements json.Unmarshaler.
// It supports string, object (e.g. pq.NullTime and friends)
// and null input.
func (t *Time) UnmarshalJSON(data []byte) error {
	var err error
	var v interface{}
	if err = json.Unmarshal(data, &v); err != nil {
		return err
	}
	switch x := v.(type) {
	case string:
		var ti time.Time
		if err = ti.UnmarshalJSON(data); err != nil {
			return err
		}
		*t = TimeFrom(ti)
		return nil
	case map[string]interface{}:
		ti, tiOK := x["Time"].(string)
		valid, validOK := x["Valid"].(bool)
		if !tiOK || !validOK {
			return fmt.Errorf(`json: unmarshalling object into Go value of type null.Time requires key "Time" to be of type string and key "Valid" to be of type bool; found %T and %T, respectively`, x["Time"], x["Valid"])
		}
		err = t.Time.UnmarshalText([]byte(ti))
		t.Valid = valid
		return err
	case nil:
		t.Valid = false
		return nil
	default:
		return fmt.Errorf("json: cannot unmarshal %v into Go value of type null.Time", reflect.TypeOf(v).Name())
	}
}
开发者ID:robinjha,项目名称:clair,代码行数:33,代码来源:time.go

示例2: QueryDeployVersionFiles

func QueryDeployVersionFiles(name string) {
	log.Println("QueryDeployVersionFiles:", name)
	data, err := util.JsonRpcData("http://" + deployUrl + "/rpc/files?version=" + name)
	if err != nil {
		log.Println(err)
		return
	}
	var files []interface{} = data["files"].([]interface{})

	versionLock.Lock()
	defer versionLock.Unlock()

	cur := FindVersion(name)
	if cur == nil {
		return
	}
	cur.filesQed = true
	cur.Files = make([]VerFile, len(files))
	for i := 0; i < len(files); i++ {
		f := files[i].(map[string]interface{})
		name := f["Name"].(string)
		size := int64(f["Size"].(float64))
		modtime := f["ModTime"].(string)
		var t time.Time
		t.UnmarshalJSON([]byte("\"" + modtime + "\""))
		cur.Files[i] = VerFile{name, size, t, false}
		//log.Println("f:", i, name, size, modtime, t, err)
	}
	log.Println("QueryDeployVersionFiles:", name, len(cur.Files))
	CheckVersionLocalState(cur)
	//	dbg, _ := json.Marshal(cur.Files)
	//	log.Println("4:", string(dbg))
}
开发者ID:ChristophPech,项目名称:servertest,代码行数:33,代码来源:versions.go

示例3: UnmarshalJSON

// UnmarshalJSON implements json.Unmarshaler.
//
// Unmarshals a JSON entry into the underlying type. The entry is expected to
// contain a string corresponding to one of the enum's keys.
func (t *Time) UnmarshalJSON(data []byte) error {
	var value time.Time
	if err := value.UnmarshalJSON(data); err != nil {
		return err
	}
	*t = Time(value.UTC())
	return nil
}
开发者ID:shishkander,项目名称:luci-go,代码行数:12,代码来源:time.go

示例4: MtimeGet

func (self *BundleFileMD) MtimeGet() (*time.Time, error) {
	tstr, err := self.bundle.bm.BundleFileStringGet(self.bundle.user, self.bundle.id, self.id, "mtime")
	if err != nil {
		return nil, err
	}
	if tstr == "" {
		return nil, nil
	}
	t := time.Time{}
	err = t.UnmarshalJSON([]byte(tstr))
	return &t, err
}
开发者ID:EMSL-MSC,项目名称:pacifica-uploader-2.0,代码行数:12,代码来源:bundlemanager.go

示例5: UnmarshalJSON

// UnmarshalJSON will unmarshal a JSON value into
// the propert representation of that value.
func (ns *Time) UnmarshalJSON(text []byte) error {
	ns.Valid = false
	txt := string(text)
	if txt == "null" || txt == "" {
		return nil
	}

	t := time.Time{}
	err := t.UnmarshalJSON(text)
	if err == nil {
		ns.Time = t
		ns.Valid = true
	}

	return err
}
开发者ID:ryanzec,项目名称:going,代码行数:18,代码来源:time.go

示例6: ParseTime

// ParseTime converts given string to Time object.
//
// It tries to parse the string as int, if it succeeds it tries to interpret the
// number as Epoch time in seconds. If the resulting time is greater than
// 2100/01/01 00:00:00 UTC, it interprets the given number as Epoch in
// milliseconds.
//
// If the given string does not represent a decimal integer number,
// ParseTime tries to parse it as a quoted string in RFC 3339 format, with
// sub-second precision added if present.
func ParseTime(str string) (time.Time, error) {
	if val, err := strconv.ParseInt(str, 10, 64); err == nil {
		sec := val
		nsec := int64(0)
		// Heuristic: if the val is too high, treat it as milliseconds rather
		// than seconds.
		if val > timeSecEpochTreshold {
			sec = val / 1000
			nsec = (val - sec*1000) * 1000 * 1000
		}
		return time.Unix(sec, nsec).UTC(), nil
	}

	t := time.Time{}
	err := t.UnmarshalJSON([]byte(`"` + str + `"`))
	return t, err
}
开发者ID:PlanitarInc,项目名称:go-simplequery,代码行数:27,代码来源:strconv.go

示例7: TestNewFromJSON_1

func TestNewFromJSON_1(t *testing.T) {
	payload := []byte("payload")
	timeStr := "2015-11-01T13:32:36.748674638+01:00"
	var t0 time.Time
	_ = t0.UnmarshalJSON([]byte(fmt.Sprintf("\"%s\"", timeStr)))

	jsonBlob := []byte(`{
		"Timestamp":"2015-11-01T13:32:36.748674638+01:00",
		"Payload":"cGF5bG9hZA=="}`)
	it0, _ := NewFromJSON(jsonBlob)
	if !it0.Timestamp.Equal(t0) {
		t.Fail()
	}
	if !bytes.Equal(it0.Payload, payload) {
		t.Fail()
	}
}
开发者ID:SudoQ,项目名称:satchel,代码行数:17,代码来源:item_test.go

示例8: poll

func poll(w http.ResponseWriter, r *http.Request) {
  engine = lmk.NewEngineFromFile(lmk_config_file)
  w.Header().Set("Content-Type", "text/plain")

  u, _ := url.Parse(os.Getenv("REDISTOGO_URL"))
  c, err := redis.Dial("tcp", u.Host)
  if err != nil {
    fmt.Println("Could not connect to redis.")
    return
  }

  pass, _ := u.User.Password()
  c.Do("AUTH", pass)

  exists, _ := redis.Bool(c.Do("EXISTS", "last_update"))
  if !exists {
    fmt.Println(w, "No value for last_update, running all.")
    for _, rule := range engine.Rules() {
      fmt.Fprintln(w, "Running "+rule.Name())
      engine.Run(rule)
    }
  } else {
    var last_update time.Time
    last_update_str, _ := redis.String(c.Do("GET", "last_update"))
    last_update.UnmarshalJSON([]byte(last_update_str))

    fmt.Fprintln(w, "Last updated "+last_update.String())
    for _, rule := range engine.RulesToPoll(last_update) {
      fmt.Println("Running " + rule.Name())
      fmt.Fprintln(w, "Running "+rule.Name())
      engine.Run(rule)
    }
  }

  bytes, _ := time.Now().MarshalJSON()
  c.Send("SET", "last_update", string(bytes))
  c.Flush()
  c.Receive()
}
开发者ID:jeady,项目名称:lmk,代码行数:39,代码来源:heroku.go

示例9: poll

func poll(w http.ResponseWriter, r *http.Request) {
	engine, context := begin_lmk_request(r)
	w.Header().Set("Content-Type", "text/plain")

	var configs []Config
	q := datastore.NewQuery("Config").Filter("Key =", "last_update")
	q.GetAll(context, &configs)
	if len(configs) < 1 {
		context.Infof("No value for last_update, running all.")
		for _, rule := range engine.Rules() {
			fmt.Fprintln(w, "Running "+rule.Name())
			engine.Run(rule)
		}
	} else {
		var last_update time.Time
		last_update.UnmarshalJSON([]byte(configs[0].Value))

		fmt.Fprintln(w, "Last updated "+last_update.String())
		for _, rule := range engine.RulesToPoll(last_update) {
			context.Infof("Running " + rule.Name())
			fmt.Fprintln(w, "Running "+rule.Name())
			engine.Run(rule)
		}
	}

	bytes, _ := time.Now().MarshalJSON()
	c := Config{
		Key:   "last_update",
		Value: string(bytes),
	}
	bKey := datastore.NewKey(context, "Config", "Key", 0, nil)
	_, err := datastore.Put(context, bKey, &c)

	if err != nil {
		fmt.Fprintln(w, "Problem putting: "+err.Error())
	}
}
开发者ID:jeady,项目名称:lmk,代码行数:37,代码来源:appengine.go

示例10: Fuzz

func Fuzz(data []byte) int {
	var t time.Time
	if err := t.UnmarshalText(data); err != nil {
		return 0
	}
	data1, err := t.MarshalText()
	if err != nil {
		panic(err)
	}
	var t1 time.Time
	if err := t1.UnmarshalText(data1); err != nil {
		panic(err)
	}
	if !fuzz.DeepEqual(t, t1) {
		fmt.Printf("t0: %#v\n", t)
		fmt.Printf("t1: %#v\n", t1)
		panic("bad MarshalText")
	}

	data2, err := t.GobEncode()
	if err != nil {
		panic(err)
	}
	var t2 time.Time
	if err := t2.GobDecode(data2); err != nil {
		panic(err)
	}
	if !fuzz.DeepEqual(t, t2) {
		fmt.Printf("t0: %#v\n", t)
		fmt.Printf("t2: %#v\n", t2)
		panic("bad GobEncode")
	}

	data3, err := t.MarshalBinary()
	if err != nil {
		panic(err)
	}
	var t3 time.Time
	if err := t3.UnmarshalBinary(data3); err != nil {
		panic(err)
	}
	if !fuzz.DeepEqual(t, t3) {
		fmt.Printf("t0: %#v\n", t)
		fmt.Printf("t3: %#v\n", t3)
		panic("bad MarshalBinary")
	}

	data4, err := t.MarshalJSON()
	if err != nil {
		panic(err)
	}
	var t4 time.Time
	if err := t4.UnmarshalJSON(data4); err != nil {
		panic(err)
	}
	if !fuzz.DeepEqual(t, t4) {
		fmt.Printf("t0: %#v\n", t)
		fmt.Printf("t4: %#v\n", t4)
		panic("bad MarshalJSON")
	}

	data5, err := t.MarshalText()
	if err != nil {
		panic(err)
	}
	var t5 time.Time
	if err := t5.UnmarshalText(data5); err != nil {
		panic(err)
	}
	if !fuzz.DeepEqual(t, t5) {
		fmt.Printf("t0: %#v\n", t)
		fmt.Printf("t5: %#v\n", t5)
		panic("bad MarshalText")
	}

	data6 := t.Format(time.RFC3339Nano)
	t6, err := time.Parse(time.RFC3339Nano, data6)
	if err != nil {
		panic(err)
	}
	if !fuzz.DeepEqual(t, t6) {
		fmt.Printf("t0: %#v\n", t)
		fmt.Printf("t6: %#v\n", t6)
		panic("bad Format")
	}
	return 1
}
开发者ID:sjn1978,项目名称:go-fuzz,代码行数:87,代码来源:main.go


注:本文中的Time.Time.UnmarshalJSON方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。