本文整理汇总了Golang中json.Unmarshal函数的典型用法代码示例。如果您正苦于以下问题:Golang Unmarshal函数的具体用法?Golang Unmarshal怎么用?Golang Unmarshal使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Unmarshal函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: 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)
}
}
示例2: TestJsonCodec
func TestJsonCodec(t *testing.T) {
m1 := []byte(`{"site":"xxx", "dep":[], "op":{"$t":[ "Hello World", {"$s":5}, {"$d":3} ] } }`)
mut, err := DecodeMutation(m1)
if err != nil {
t.Fatal(err.String())
return
}
m1b, _, err := EncodeMutation(mut, EncNormal)
if err != nil {
t.Fatal(err.String())
return
}
d1 := make(map[string]interface{})
d2 := make(map[string]interface{})
err = json.Unmarshal(m1, &d1)
if err != nil {
t.Fatal(err.String())
return
}
err = json.Unmarshal(m1b, &d2)
if err != nil {
t.Fatal(err.String())
return
}
if !compareJson(d1, d2) {
t.Fatalf("Decoding and Encoding changed the mutation content:\n%v\n%v\n", string(m1), string(m1b))
return
}
}
示例3: GetSubscriptions
func (ts *Tribserver) GetSubscriptions(args *tribproto.GetSubscriptionsArgs, reply *tribproto.GetSubscriptionsReply) os.Error {
//check if user exists
suscribersJson, stat, err := ts.tm.GET(args.Userid + SUBSCRIPTIONS)
if err != nil {
return err
}
if stat == storageproto.OK {
subscribers := make(map[string]bool)
err := json.Unmarshal(suscribersJson, &subscribers)
if err != nil {
return err
}
reply.Userids = make([]string, len(subscribers))
i := 0
//add each userid in the suscribers list to the reply arg
for key, _ := range subscribers {
s := new(string)
err = json.Unmarshal([]byte(key), s)
if err != nil {
return err
}
reply.Userids[i] = *s
i++
}
reply.Status = tribproto.OK
} else {
reply.Status = tribproto.ENOSUCHUSER
}
return nil
}
示例4: unmarshal
/*
json.Unmarshal wrapper
extracts json data into new interface and returns populated array of interfaces and any errors raised
*/
func (this *Neo4j) unmarshal(s string) (dataSet map[int]*NeoTemplate, err os.Error) {
var (
templateNode map[string]interface{} // blank interface for json.Unmarshal; used for node lvl data
templateSet []map[string]interface{} // array of blank interfaces for json.Unmarshal
)
dataSet = make(map[int]*NeoTemplate) // make it ready for elements
err = json.Unmarshal([]byte(s), &templateNode) // unmarshal json data into blank interface. the json pkg will populate with the proper data types
if err != nil { // fails on multiple results
err = json.Unmarshal([]byte(s), &templateSet) // if unable to unmarshal into single template, try an array of templates instead. If that fails, raise an error
if err != nil {
return nil, err
}
for _, v := range templateSet {
data, err := this.unmarshalNode(v) // append NeoTemplate into the data set
if err != nil {
return nil, err
}
dataSet[len(dataSet)] = data // new array element containing data
}
} else {
template, err := this.unmarshalNode(templateNode)
if err != nil {
return nil, err
}
dataSet[0] = template // just a single result
}
return
}
示例5: TestObjectIdJSONUnmarshalingError
func (s *S) TestObjectIdJSONUnmarshalingError(c *C) {
v := jsonType{}
err := json.Unmarshal([]byte(`{"Id":"4d88e15b60f486e428412dc9A"}`), &v)
c.Assert(err, Matches, `Invalid ObjectId in JSON: "4d88e15b60f486e428412dc9A"`)
err = json.Unmarshal([]byte(`{"Id":"4d88e15b60f486e428412dcZ"}`), &v)
c.Assert(err, Matches, `Invalid ObjectId in JSON: "4d88e15b60f486e428412dcZ" \(invalid hex char: 90\)`)
}
示例6: testJsonGet
func testJsonGet(server *Server, uri string, jsonResponse string, t *testing.T) bool {
// Send a POST message to create a document
u, ok := NewURI(uri)
if !ok {
t.Errorf("Failed to parse URI")
return false
}
ch := make(chan bool)
w := NewResponseWriter()
req := &GetRequest{Request{w, "", ch, ClientOrigin, u}}
server.Get(req)
<-ch
if w.StatusCode != 200 {
t.Errorf("Expected status code 200")
return false
}
j1 := make(map[string]interface{})
if err := json.Unmarshal(w.Buffer.Bytes(), &j1); err != nil {
t.Errorf("Failed to parse JSON response: %v", err)
return false
}
j2 := make(map[string]interface{})
if err := json.Unmarshal([]byte(jsonResponse), &j2); err != nil {
t.Errorf("Malformed JSON in test case: %v\n", jsonResponse, err)
return false
}
if !compareJson(j1, j2) {
t.Errorf("Expected\n\t%v\ninstead got\n\t%v\n", jsonResponse, string(w.Buffer.Bytes()))
return false
}
return true
}
示例7: 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))
}
示例8: TestJsonCodec2
func TestJsonCodec2(t *testing.T) {
m1 := []byte(`{"site":"xxx", "dep":["abc"], "op":{"$t":[ "Hello World", {"$s":5}, {"$d":3} ] } }`)
var mut Mutation
err := json.Unmarshal(m1, &mut)
if err != nil {
t.Fatal(err.String())
return
}
if mut.Site != "xxx" || mut.Operation.Kind != StringOp || mut.Dependencies[0] != "abc" {
t.Fatal("Decoding failed")
}
m1b, err := json.Marshal(&mut)
if err != nil {
t.Fatal(err.String())
return
}
d1 := make(map[string]interface{})
d2 := make(map[string]interface{})
err = json.Unmarshal(m1, &d1)
if err != nil {
t.Fatal(err.String())
return
}
err = json.Unmarshal(m1b, &d2)
if err != nil {
t.Fatal(err.String())
return
}
if !compareJson(d1, d2) {
t.Fatalf("Decoding and Encoding changed the mutation content:\n%v\n%v\n", string(m1), string(m1b))
return
}
}
示例9: main
func main() {
// Read the string
inputReader := bufio.NewReader(os.Stdin)
var info = Metadata{"", uint32(0), nil}
var cmd = Command{"", nil, nil, nil, ""}
infoJson, err := inputReader.ReadString('\n')
if err != nil {
log.Exit(err)
} else {
json.Unmarshal(infoJson, &info)
}
bpt, bperr := bptree.NewBpTree(info.Filename, info.Keysize, info.Fieldsizes)
if !bperr {
log.Exit("Failed B+ tree creation")
} else {
fmt.Println("ok")
}
alive := true
for alive {
cmdJson, err := inputReader.ReadString('\n')
if err != nil {
alive = false
break
}
if cmdJson == "q\n" {
alive = false
} else {
json.Unmarshal(cmdJson, &cmd)
if cmd.Op == "insert" {
result := bpt.Insert(cmd.LeftKey, cmd.Fields)
fmt.Println(result)
} else if cmd.Op == "find" {
records, ack := bpt.Find(cmd.LeftKey, cmd.RightKey)
for record := range records {
json.Marshal(os.Stdout, map[string]interface{}{
"key": record.GetKey(),
"value": record.AllFields()})
fmt.Println()
ack <- true
}
fmt.Println("end")
} else if cmd.Op == "visualize" {
bptree.Dotty(cmd.FileName, bpt)
} else if cmd.Op == "prettyprint" {
s := fmt.Sprintln(bpt)
f, _ := os.Open(cmd.FileName, os.O_RDWR|os.O_CREAT, 0666)
f.Write([]byte(s))
f.Close()
}
}
}
fmt.Println("exited")
}
示例10: TestCreateUserAccount
func TestCreateUserAccount(t *testing.T) {
ds := inmemory.NewInMemoryDataStore()
wm := webmachine.NewWebMachine()
wm.AddRouteHandler(account.NewCreateAccountRequestHandler(ds, ds))
buf := bytes.NewBufferString(`{"role": 9999999999999999, "name": "George Washington", "username": "firstpresident", "email":"[email protected]", "phone_number": "+1-405-555-5555", "address": "Valley Forge"}`)
oldUser := new(dm.User)
json.Unmarshal(buf.Bytes(), &oldUser)
req, _ := http.NewRequest(webmachine.POST, "http://localhost/api/v1/json/account/user/create/", buf)
req.Header.Set("Content-Type", webmachine.MIME_TYPE_JSON+"; charset=utf-8")
req.Header.Set("Accept", webmachine.MIME_TYPE_JSON+"; charset=utf-8")
req.Header.Set("Accept-Charset", "utf-8")
req.Header.Set("Accept-Encoding", "identity")
req.Header.Set("Accept-Language", "en-us")
req.Header.Set("Connection", "close")
resp := webmachine.NewMockResponseWriter(req)
wm.ServeHTTP(resp, req)
if resp.StatusCode != 200 {
t.Error("Expected 200 status code but received ", resp.StatusCode)
}
if resp.Header().Get("Content-Type") != req.Header.Get("Accept") {
t.Error("Expected Content-Type \"", req.Header.Get("Accept"), "\" but received ", resp.Header().Get("Content-Type"))
}
user := new(dm.User)
obj := jsonhelper.NewJSONObject()
err := json.Unmarshal(resp.Buffer.Bytes(), &obj)
user.InitFromJSONObject(obj.GetAsObject("result"))
if err != nil {
t.Error("Error while unmarshaling JSON: ", err.String())
}
if obj.GetAsString("status") != "success" {
t.Error("Expected status = \"success\", but was \"", obj.GetAsString("status"), "\"")
}
if user.Name != oldUser.Name {
t.Error("Expected name = \"", oldUser.Name, "\", but was ", user.Name)
}
if user.Username != oldUser.Username {
t.Error("Expected username = \"", oldUser.Username, "\", but was ", user.Username)
}
if user.Email != oldUser.Email {
t.Error("Expected email = \"", oldUser.Email, "\", but was ", user.Email)
}
if user.PhoneNumber != oldUser.PhoneNumber {
t.Error("Expected phone_number = \"", oldUser.PhoneNumber, "\", but was ", user.PhoneNumber)
}
if user.Address != oldUser.Address {
t.Error("Expected address = \"", oldUser.Address, "\", but was ", user.Address)
}
if user.Role != dm.ROLE_STANDARD {
t.Error("Expected role = ", dm.ROLE_STANDARD, " but was ", user.Role)
}
if user.Id == "" {
t.Error("Expected id to be populated, but was empty")
}
}
示例11: TestUpdateDocument
func TestUpdateDocument(t *testing.T) {
initDatabase(t)
doc := map[string]string{"a": "12", "b": "this is a test"}
database := NewDatabase("http://127.0.0.1:5984/test123/")
docid, revid, err := database.Create(tojs(doc))
if err != nil {
t.Error(err.String())
}
if docid == "" {
t.Error("Doc Id is null")
}
contents := map[string]string{}
data, err := database.Get(docid)
if err != nil {
t.Error(err.String())
}
json.Unmarshal(data, &contents)
if contents["a"] != "12" || contents["b"] != "this is a test" {
t.Error("parameter mismatch")
}
contents["a"] = "100"
contents["b"] = "this is a test 2"
contents["_id"] = docid
contents["_rev"] = revid
err = database.Update(docid, tojs(contents))
if err != nil {
t.Error(err.String())
}
data, err = database.Get(docid)
if err != nil {
t.Error(err.String())
}
json.Unmarshal(data, &contents)
if contents["a"] != "100" || contents["b"] != "this is a test 2" {
t.Error("parameter mismatch")
}
}
示例12: getParams
func getParams(req *jsonRequest, argTypes []reflect.Type) ([]reflect.Value, os.Error) {
params := make([]*json.RawMessage, 0)
err := json.Unmarshal(*req.Params, ¶ms)
if err != nil {
return nil, err
}
if len(params) != len(argTypes) {
return nil, os.ErrorString("Incorrect number of parameters.")
}
args := make([]reflect.Value, 0, len(argTypes))
for i, argType := range argTypes {
argPointerType := argType
if argPointerType.Kind() == reflect.Ptr {
argPointer := reflect.New(argType)
err := json.Unmarshal(*params[i], argPointer.Interface())
if err != nil {
return nil, os.ErrorString("Type mismatch parameter " + strconv.Itoa(i+1) + ".")
}
args = append(args, reflect.Indirect(argPointer))
} else {
var arg reflect.Value
var v interface{}
err := json.Unmarshal(*params[i], &v)
if err != nil {
return nil, os.ErrorString("Type mismatch parameter " + strconv.Itoa(i+1) + ".")
}
value := reflect.ValueOf(v)
if value.Type() == argType {
arg = reflect.ValueOf(v)
} else if value.Type().Kind() == reflect.Float32 || value.Type().Kind() == reflect.Float64 {
if argType.Kind() == reflect.Int || argType.Kind() == reflect.Int8 ||
argType.Kind() == reflect.Int16 || argType.Kind() == reflect.Int32 ||
argType.Kind() == reflect.Int64 {
arg = reflect.ValueOf(int(v.(float64)))
} else {
return nil, os.ErrorString("Type mismatch parameter " + strconv.Itoa(i+1) + ".")
}
} else {
return nil, os.ErrorString("Type mismatch parameter " + strconv.Itoa(i+1) + ".")
}
args = append(args, reflect.Value(arg))
}
}
return args, nil
}
示例13: TestCreateDocument
func TestCreateDocument(t *testing.T) {
initDatabase(t)
test_document := struct {
a int
b string
}{12, "this is a test"}
database := NewDatabase("http://127.0.0.1:5984/test123/")
docid, _, err := database.Create(tojs(test_document))
if err != nil {
t.Error(err.String())
}
if docid == "" {
t.Error("Doc Id is null")
}
var contents struct {
A int
B string
}
data, err := database.Get(docid)
if err != nil {
t.Error(err.String())
}
json.Unmarshal(data, &contents)
if contents.A != 12 || contents.B != "this is a test" {
t.Error("parameter mismatch")
}
}
示例14: GetListRPC
func (ss *Storageserver) GetListRPC(args *storageproto.GetArgs, reply *storageproto.GetListReply) os.Error {
reply.Lease = storageproto.LeaseStruct{}
reply.Lease.Granted = false
reply.Lease.ValidSeconds = 0
if args.WantLease && ss.handleLeaseRequest(args) { // grant the lease if possible
reply.Lease.Granted = true
reply.Lease.ValidSeconds = LEASE_SECONDS
}
val, status := ss.tm.GET(args.Key)
reply.Status = status
if status == storageproto.OK {
set := make(map[string]bool)
err := json.Unmarshal(val, &set)
if err != nil {
reply.Status = storageproto.EPUTFAILED
} else {
reply.Value = make([]string, len(set))
i := 0
for key, _ := range set {
reply.Value[i] = key
i++
}
}
}
return nil
}
示例15: AppEngineVerify
func AppEngineVerify(r *http.Request) string {
if err := r.ParseForm(); err != nil {
return "Anonymous"
}
token := r.FormValue("assertion")
url := "https://browserid.org/verify"
bodytype := "application/x-www-form-urlencoded"
body := strings.NewReader("assertion=" + token + "&audience=" + r.Host)
var response_body []byte
c := appengine.NewContext(r)
client := urlfetch.Client(c)
res, err := client.Post(url, bodytype, body)
if err != nil {
fmt.Println("err=", err)
return "Anonymous"
} else {
response_body, _ = ioutil.ReadAll(res.Body)
res.Body.Close()
}
var f interface{}
json.Unmarshal(response_body, &f)
m := f.(map[string]interface{})
return fmt.Sprintf("%s", m["email"])
}