doufuhao8085 2014-12-25 00:32
浏览 63
已采纳

根据参数值在Golang中解码传入的JSON

I am trying to decode an incoming JSON in my REST API written in Go. I am using decoder.Decode() function and my problem is that I need to apply a certain rules on which struct should be used in the process of decoding because sometimes the JSON contains:

"type": {
    "type" : "string",
    "maxLength" : 30
},

and sometimes:

"type": {
    "type" : "integer",
    "max" : 30,
    "min" : 10
},

I somehow need to tell Go that "If the type.type is string, use this struct (type Type_String struct) and if the type.type is integer, use other struct (type Type_Integer struct)". I am not really sure how to do it. One solution which is on my mind is to make an universal struct with the all possible properties, use it on any kind of object and then filter the properties based on the type property but this is just so dirty. I guess I can also write my own decoder but that seems also a bit strange.

I am new to Go and I am pretty much used to the freedom JavaScript offers.

  • 写回答

2条回答 默认 最新

  • doutinghou6980 2014-12-25 01:03
    关注

    You can always decode to interface{} like mentioned here: How to access interface fields on json decode?

    http://play.golang.org/p/3z8-unhsH4

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    var one string = `{"type": {"type": "string", "maxLength":30}}`
    var two string = `{"type": {"type": "integer", "max":30, "min":10}}`
    
    func f(data map[string]interface{}) {
        t := data["type"]
        typemap := t.(map[string]interface{})
        t2 := typemap["type"].(string)
        switch t2 {
        case "string":
            fmt.Println("maxlength:", typemap["maxLength"].(float64))
        case "integer":
    
            fmt.Println("max:", typemap["max"].(float64))
        default:
            panic("oh no!")
        }
    }
    
    func main() {
        var jsonR map[string]interface{}
        err := json.Unmarshal([]byte(one), &jsonR)
        if err != nil {
            panic(err)
        }
        f(jsonR)
        json.Unmarshal([]byte(two), &jsonR)
        f(jsonR)
    }
    

    The idea is to unmarshal to map[string]interface{} and then cast and compare before accessing values.

    In the above code, the f function does the cast and compare. Given this poor json, I used poor variable name, t and t2 to represent the json values of "type" at different depths. Once t2 has the value, the switch statement does something with the "string" or the "integer" and what it does is print the maxLength or the max value.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常