在通用函数中如何解码 JSON?

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

how do I decode json in a generic function

问题

在Go语言中,你可以这样实现(假设T是一个类似于C++、C#、Java等语言中的模板):

import (
    "encoding/json"
    "net/http"
)

func DecodeFormToJson(r *http.Request, t *T) (err error) {
    decoder := json.NewDecoder(r.Body)
    err = decoder.Decode(&t)
    return
}

这段代码使用了Go语言的encoding/json包来将HTTP请求的表单数据解码为JSON格式,并将结果存储到t中。注意,T需要是一个合适的类型,以便能够正确解码JSON数据。

英文:

How do I do something like this (assuming T is a template like in C++, C#, Java etc...) in golang:

func DecodeFormToJson(r *http.Request, t *T) err error {
	decoder := json.NewDecoder(r.Body)
    err = decoder.Decode(&t)
    return 
}

答案1

得分: 3

只需简单地使用interface{},这正是Decoder.Decode使用的方式,例如:

func proxyDecode(r io.Reader, i interface{}) error {
    dec := json.NewDecoder(r)
    return dec.Decode(i)
}
英文:

Simply using an interface{} which is what Decoder.Decode uses anyway, for example:

func proxyDecode(r io.Reader, i interface{}) error {
	dec := json.NewDecoder(r)
	return dec.Decode(i)
}

huangapple
  • 本文由 发表于 2014年8月3日 21:07:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/25104951.html
匿名

发表评论

匿名网友

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

确定