如何解析JSON字符串以构造 [英] How to parse JSON string to struct

查看:120
本文介绍了如何解析JSON字符串以构造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有请求的struct,值是可选的:

I have struct of Request, value is optional:

type Request struct {
    Operation string      `json:"operation"`
    Key string            `json:"key"`
    Value string          `json:"value"`
}

应该将json字符串解析为struct ^的函数

And function that should parse json string to struct^

go func() {
    s := string("{'operation': 'get', 'key': 'example'}")
    data := Request{}
    json.Unmarshal([]byte(s), data)
    log.Printf("Operation: %s", data.Operation)
}

出于某种原因data.Operation为空.怎么了?

For some reason data.Operation is empty. What is wrong here?

推荐答案

两个问题,首先,您的json无效,它需要使用"而不是'

Two problems, first, your json is invalid, it needs to use " instead of '

第二,您必须解组到&data而不是data

Second, you have to unmarshal into &data and not to data

https://play.golang.org/p/zdMq5_ex8G

package main

import (
    "fmt"
    "encoding/json"
)

type Request struct {
    Operation string      `json:"operation"`
    Key string            `json:"key"`
    Value string          `json:"value"`
}

func main() {
    s := string(`{"operation": "get", "key": "example"}`)
    data := Request{}
    json.Unmarshal([]byte(s), &data)
    fmt.Printf("Operation: %s", data.Operation)
}

旁注,如果您一直在检查错误,就会发现:

Side note, you would have seen this, if you would have been checking your errors:

err := json.Unmarshal([]byte(s), data)
if err != nil {
    fmt.Println(err.Error()) 
    //json: Unmarshal(non-pointer main.Request)
}

s := string("{'operation': 'get', 'key': 'example'}")
//...
err := json.Unmarshal([]byte(s), data)
if err != nil {
    fmt.Println(err.Error()) 
    //invalid character '\'' looking for beginning of object key string
}

这篇关于如何解析JSON字符串以构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆