处理来自POST请求的JSON响应

huangapple go评论75阅读模式
英文:

Handle response from post request to Json

问题

你可以使用以下代码来处理JSON变量:

type ResponseFromPost struct {
    N_expediente string `json:"n_expediente"`
    Enviar       string `json:"enviar"`
}

func main() {
    // ...

    res, err := client.Do(req)
    if err != nil {
        return
    }

    defer res.Body.Close()

    body, err := ioutil.ReadAll(res.Body)

    var re []ResponseFromPost
    err = json.Unmarshal(body, &re)
    if err != nil {
        return
    }

    for _, r := range re {
        fmt.Println(r.N_expediente)
        fmt.Println(r.Enviar)
    }
}

这样,你就可以将服务器发送的JSON数据解析为ResponseFromPost结构体的切片,并访问其中的变量。在上面的代码中,我们使用了json标签来指定JSON字段与结构体字段之间的映射关系。

英文:

I'm using the following code to get a response from a server after a post request:

type ResponseFromPost struct {
	N_expediente string
	Enviar string
}

func main(){

    ......

    res, err := client.Do(req)
    if err != nil {
        return
    }
	
	defer res.Body.Close()
	
	body, err := ioutil.ReadAll(res.Body)
	
	var re ResponseFromPost
	err = json.Unmarshal(body, &re)
	fmt.Println(re.Enviar);
}

With this I get:

    error: &{%!e(string=array) %!e(*reflect.rtype=&{32 2509985895 0 8 8 25 0x608170
[0x7703c0 <nil>] 0x730b80 0x69acb0 0x6116c0 0x7732c0})}

The value sent by the server is:

[{"n_expediente":"9","enviar":"2"}]

How can I use the json variables?

答案1

得分: 0

这是一个包含字符串n_expedienteenviar的对象数组的JSON。在Go语言中,你需要一个你自己定义的类型的数组:

re := []ResponseFromPost{} 
err := json.Unmarshal([]byte(`[{"n_expediente":"9","enviar":"2"}]`), &re)
fmt.Println(re[0].Enviar);

这里有一个示例,展示了你的模型需要的代码:https://play.golang.org/p/d64Sict4AG

你可能还需要根据这个示例对你的代码进行一些其他更改,比如在解析后使用切片长度作为循环的边界(for i := range re { print i }),以及为类型取一个不同的名称。

英文:

The json is an array of those objects having the strings n_expediente and enviar on each instance. In the Go you'll need an array of your type;

re := []ResponseFromPost{} 
err := json.Unmarshal([]byte(`[{"n_expediente":"9","enviar":"2"}]`), &re)
fmt.Println(re[0].Enviar);

Here's an example to show what your model needs to be https://play.golang.org/p/d64Sict4AG

You'll probably want to make some other changes to your code based on that. Like a loop bound by the length of the slice ( for i := range re { print i } ) after the unmarshal and a different name for the type.

huangapple
  • 本文由 发表于 2015年6月20日 06:32:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/30948209.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定