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


Golang json.Marshal函数代码示例

本文整理汇总了Golang中json.Marshal函数的典型用法代码示例。如果您正苦于以下问题:Golang Marshal函数的具体用法?Golang Marshal怎么用?Golang Marshal使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: NewSocketLogWriter

func NewSocketLogWriter(proto, hostport string) SocketLogWriter {
	sock, err := net.Dial(proto, hostport)
	if err != nil {
		fmt.Fprintf(os.Stderr, "NewSocketLogWriter(%q): %s\n", hostport, err)
		return nil
	}

	w := SocketLogWriter(make(chan *LogRecord, LogBufferLength))

	go func() {
		defer func() {
			if sock != nil && proto == "tcp" {
				sock.Close()
			}
		}()

		for rec := range w {
			// Marshall into JSON
			js, err := json.Marshal(rec)
			if err != nil {
				fmt.Fprint(os.Stderr, "SocketLogWriter(%q): %s", hostport, err)
				return
			}

			_, err = sock.Write(js)
			if err != nil {
				fmt.Fprint(os.Stderr, "SocketLogWriter(%q): %s", hostport, err)
				return
			}
		}
	}()

	return w
}
开发者ID:v-gu,项目名称:mysqltc,代码行数:34,代码来源:socklog.go

示例2: listenForMoveRequests

func listenForMoveRequests(conn *net.TCPConn) {
	listenServe := make(chan []uint8)
	easynet.TieConnToChannel(conn, listenServe)
	for data := range listenServe {
		r := new(ttypes.BotMoveRequest)
		err := json.Unmarshal(data, r)
		easynet.DieIfError(err, "JSON error")

		if r.Kill {
			fmt.Printf("Bot on %s received kill signal\n", os.Args[0])
			os.Exit(0)
		}

		fmt.Printf("Bot at %d, %d received messages: %v\n", r.YourX, r.YourY, r.Messages)
		fmt.Printf("  Sees other bots: %v\n", r.OtherBots)
		//Do something

		response := new(ttypes.BotMoveResponse)
		if r.YourY < 5 {
			response.MoveDirection = "up"
		} else if r.YourY > 5 {
			response.MoveDirection = "down"
		}
		// response.BroadcastMessage = fmt.Sprintf("'I am %v at %d, %d'", os.Args[0], r.YourX, r.YourY)
		responseString, err := json.Marshal(response)
		easynet.DieIfError(err, "JSON marshal error")
		conn.Write(responseString)
	}
}
开发者ID:jmptrader,项目名称:Tecellate,代码行数:29,代码来源:test.go

示例3: TestOT

func TestOT(t *testing.T) {
	text1 := "{\"_rev\":0, \"_data\":{\"$object\":true, \"abc\":\"xyz\", \"num\": 123, \"foo\":{\"$object\":true, \"a\":1,\"b\":3}, \"arr\":{\"$array\":[1,2,3]}}}"
	dest1 := make(map[string]interface{})
	err := json.Unmarshal([]byte(text1), &dest1)
	if err != nil {
		t.Errorf("Cannot parse: %v", err)
		return
	}

	text2 := "{\"_rev\":0, \"_data\":{\"$object\":true, \"torben\":\"weis\", \"num\": 321, \"foo\":{\"$object\":true, \"a\":6,\"c\":33}, \"arr\":{\"$array\":[4,5,6]}}}"
	dest2 := make(map[string]interface{})
	err = json.Unmarshal([]byte(text2), &dest2)
	if err != nil {
		t.Errorf("Cannot parse: %v", err)
		return
	}

	m1 := DocumentMutation(dest1)
	m2 := DocumentMutation(dest2)
	var ot Transformer
	err = ot.Transform(m1, m2)
	if err != nil {
		t.Errorf("Cannot transform: %v", err)
		return
	}

	enc1, _ := json.Marshal(dest1)
	log.Println("t1=", string(enc1))
	enc2, _ := json.Marshal(dest2)
	log.Println("t2=", string(enc2))
}
开发者ID:AaronO,项目名称:lightwave,代码行数:31,代码来源:ot_test.go

示例4: CreateUser

func (ts *Tribserver) CreateUser(args *tribproto.CreateUserArgs, reply *tribproto.CreateUserReply) os.Error {
	//check if user exists
	_, stat, err := ts.tm.GET(args.Userid + LAST)
	if err != nil {
		return err
	}

	//return if exists already
	if stat == storageproto.OK {
		log.Printf("create user: user already exists")
		reply.Status = tribproto.EEXISTS

	} else {
		log.Printf("Creating new user")
		//initialize the 3 maps for the user
		val, _ := json.Marshal(0)
		ts.tm.PUT(args.Userid+LAST, val)
		val, _ = json.Marshal(make(map[string]bool))
		ts.tm.PUT(args.Userid+SUBSCRIPTIONS, val)
		log.Printf("FInished creating new user %s", args.Userid)
	}

	log.Printf("returning nil from create user")
	return nil
}
开发者ID:ahuseynov,项目名称:distTrib,代码行数:25,代码来源:server.go

示例5: MarshalJSON

func (p *Point) MarshalJSON() ([]byte, os.Error) {
	x, ex := json.Marshal(p.x)
	if ex != nil {
		return nil, ex
	}
	y, ey := json.Marshal(p.y)
	if ey != nil {
		return nil, ey
	}
	return []byte(fmt.Sprintf("{\"x\":%s,\"y\":%s}", x, y)), nil
}
开发者ID:ebering,项目名称:zellij,代码行数:11,代码来源:json.go

示例6: TestQuorumStrings

func TestQuorumStrings(t *testing.T) {
	out, err := json.Marshal(QUORUM)
	fatalIf(t, err != nil, "Couldn't marshal QuorumValue: %v", err)
	fatalIf(t, string(out) != `"quorum"`, "Got wrong value: '%s'", out)
	out, err = json.Marshal(ALL)
	fatalIf(t, err != nil, "Couldn't marshal QuorumValue: %v", err)
	fatalIf(t, string(out) != `"all"`, "Got wrong value: '%s'", out)
	out, err = json.Marshal(QuorumValue(4))
	fatalIf(t, err != nil, "Couldn't marshal QuorumValue: %v", err)
	fatalIf(t, string(out) != `4`, "Got wrong value: '%s'", out)
}
开发者ID:abneptis,项目名称:riak,代码行数:11,代码来源:props_test.go

示例7: MarshalJSON

func (self QuorumValue) MarshalJSON() (out []byte, err os.Error) {
	switch self {
	case QUORUM:
		out, err = json.Marshal("quorum")
	case ALL:
		out, err = json.Marshal("all")
	default:
		out, err = json.Marshal(int(self))
	}
	return
}
开发者ID:abneptis,项目名称:riak,代码行数:11,代码来源:props.go

示例8: main

func main() {
session, err := mgo.Mongo("localhost") // comma separated
	if err != nil {
		panic(err)
	}
	defer session.Close() // should keep connection pool perhaps?

	// Optional. Switch the session to a monotonic behavior.
	session.SetMode(mgo.Monotonic, true)

	c := session.DB("test").C("people")
	err = c.Insert(&Person{"Ale", "+55 53 8116 9639"},
		&Person{"Cla", "+55 53 8402 8510"})
	if err != nil {
		panic(err)
	}

	result := Person{}
	err = c.Find(bson.M{}).One(&result) 
	if err != nil {
		panic(err)
	}
	bytes, err2 := json.Marshal(result)
	if err2 != nil {
		panic(err2)
	}
	fmt.Println("person:", string(bytes))
	
	iter, err := c.Find(bson.M{}).Iter()
	if err != nil {
		panic(err)
	}
	for {
		err = iter.Next(&result)
		if err != nil {
			fmt.Println("err returned from iter:", err)
			break
		}
		//   fmt.Fprintln(w, result.Id)
		bytes, err2 := json.Marshal(result)
		if err2 != nil {
			panic(err2)
		}
		fmt.Println(string(bytes))

	}
	if err != nil {
		panic(err)
	}

}
开发者ID:gregworley,项目名称:go-doodles,代码行数:51,代码来源:mailingListExampleIter.go

示例9: encodeResult

func encodeResult(key string, result *FetchResult) (encoded []byte, err os.Error) {
	// Copy of FetchResult struct with new field Key and base64-encoded Body.
	// This is ugly and violates DRY principle.
	// But also, it allows to extract fetcher as separate package.
	var report struct {
		Key        string            "key"
		Url        string            "url"
		Success    bool              "success"
		Status     string            "status"
		StatusCode int               "status_code"
		Headers    map[string]string "headers"
		Content    string            "content"
		Cached     bool              "cached"
		Visited    string            "visited"
		FetchTime  uint              "fetch_time"
		TotalTime  uint              "total_time"
	}
	report.Key = key
	report.Url = result.Url
	report.Success = result.Success
	report.Status = result.Status
	report.StatusCode = result.StatusCode
	report.Headers = result.Headers
	report.Cached = result.Cached
	report.Visited = time.UTC().Format(HeroshiTimeFormat)
	report.FetchTime = result.FetchTime
	report.TotalTime = result.TotalTime
	content_encoded := make([]byte, base64.StdEncoding.EncodedLen(len(result.Body)))
	base64.StdEncoding.Encode(content_encoded, result.Body)
	report.Content = string(content_encoded)

	encoded, err = json.Marshal(report)
	if err != nil {
		encoded = nil
		fmt.Fprintf(os.Stderr, "Url: %s, error encoding report: %s\n",
			result.Url, err.String())

		// Most encoding errors happen in content. Try to recover.
		report.Content = ""
		report.Status = err.String()
		report.Success = false
		report.StatusCode = 0
		encoded, err = json.Marshal(report)
		if err != nil {
			encoded = nil
			fmt.Fprintf(os.Stderr, "Url: %s, error encoding recovery report: %s\n",
				result.Url, err.String())
		}
	}
	return
}
开发者ID:GunioRobot,项目名称:heroshi,代码行数:51,代码来源:worker_main.go

示例10: BenchmarkJsonFieldSet

func BenchmarkJsonFieldSet(b *testing.B) {
	data, _ := json.Marshal(testObj)
	client.Set("tjs", data)

	for i := 0; i < b.N; i++ {
		var tt testType
		data, _ := client.Get("tjs")
		json.Unmarshal(data, &tt)
		tt.A = "z"
		data, _ = json.Marshal(tt)
		client.Set("tjs", data)
	}
	client.Del("tjs")
}
开发者ID:rjmcguire,项目名称:redis.go,代码行数:14,代码来源:redis_test.go

示例11: AddToList

func (tm *TribMap) AddToList(key string, element []byte) (int, os.Error) {
	tm.lock.Lock()
	defer tm.lock.Unlock()
	_, ok := tm.data[key]
	var set map[string]bool
	var err os.Error
	if !ok {
		set = make(map[string]bool)
	} else {
		set, err = tm.GetSet(key)
		if err != nil {
			return storageproto.EPUTFAILED, err
		}
	}
	s := string(element)
	_, ok = set[s]
	if ok {
		return storageproto.EITEMEXISTS, err
	}
	set[s] = true
	val, err := json.Marshal(set)
	if err != nil {
		return storageproto.EPUTFAILED, err
	}
	tm.data[key] = val
	return storageproto.OK, nil
}
开发者ID:ahuseynov,项目名称:distTrib,代码行数:27,代码来源:storage.go

示例12: bumpGeneration

func bumpGeneration(c appengine.Context) {
	if item, err := memcache.Get(c, generationKey); err == memcache.ErrCacheMiss {
		initialValue, _ := json.Marshal(0)
		newItem := &memcache.Item{
			Key:   generationKey,
			Value: []byte(initialValue),
		}
		memcache.Set(c, newItem)
	} else {
		var oldValue int
		json.Unmarshal(item.Value, &oldValue)
		newValue := oldValue + 1
		item.Value, _ = json.Marshal(newValue)
		memcache.CompareAndSwap(c, item)
	}
}
开发者ID:shatterednirvana,项目名称:Active-Cloud-DB---Go-Edition,代码行数:16,代码来源:acdb.go

示例13: handle

func (v *jsonView) handle(w http.ResponseWriter, req *http.Request, s *session) {
	if v.checkUniqueURL != "" && req.URL.Path != v.checkUniqueURL {
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "<pre>404 page not found</pre>")
		return
	}

	d := func() (ret interface{}) {
		defer func() {
			if e := recover(); e != nil {
				if gde, ok := e.(getDataError); ok {
					ret = gde
				} else if ose, ok := e.(os.Error); ok {
					ret = getDataError{http.StatusInternalServerError, ose}
				} else {
					ret = getDataError{http.StatusInternalServerError, os.NewError(fmt.Sprintf("%v", e))}
				}
			}
		}()
		return v.getData(req, s)
	}()

	dd, e := json.Marshal(d)
	if e != nil {
		fmt.Fprintf(w, "{Code: 500, Error: %#v}", e.String())
	} else {
		w.Write(dd)
	}
}
开发者ID:Alexis211,项目名称:ajstk,代码行数:29,代码来源:util.go

示例14: RemoveFromRegistry

func RemoveFromRegistry(r *RpcService) {

	newServices := make([]*RpcService, 0)

	for _, v := range NOS.Services {
		if v != nil {
			if !v.Equal(r) {
				newServices = append(newServices, v)
			}

		}
	}
	NOS.Services = newServices
	b, err := json.Marshal(NOS)
	if err != nil {
		log.Panic(err.String())
	}
	rev, err := DC.Rev()
	if err != nil {
		log.Panic(err.String())
	}
	_, err = DC.Set("/servers/config/networkservers.conf", rev, b)
	if err != nil {
		log.Panic(err.String())
	}
}
开发者ID:andradeandrey,项目名称:skynet,代码行数:26,代码来源:registry.go

示例15: serveObject

func serveObject(val reflect.Value, w http.ResponseWriter, r *http.Request) os.Error {
	switch r.Method {
	case "HEAD", "GET", "PUT":
	default:
		return nil
		return &BadMethod{r.URL.Path, r.Method, val.Interface()}
	}

	ctype := "application/json"
	// TODO(kevlar): Content type negotiation
	w.Header().Set("Content-Type", ctype)

	if r.Method == "HEAD" {
		return nil
	}

	js, err := json.Marshal(val.Interface())
	if err != nil {
		return &FailedEncode{err, ctype, val.Interface()}
	}

	if _, err := w.Write(js); err != nil {
		return err
	}

	return nil
}
开发者ID:kylelemons,项目名称:go-resto,代码行数:27,代码来源:resource.go


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