Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用带json键的GO中的开关?_Json_Go - Fatal编程技术网

如何使用带json键的GO中的开关?

如何使用带json键的GO中的开关?,json,go,Json,Go,以下是请求后正文的示例: {"action":"do_something","id":"001"} 我举了一个简单json解析器的例子 package main import ( "encoding/json" "fmt" "net/http" ) type some_json struct { Action string `json:"action"` Id string `json:"id"` } func jsonparse(rw http

以下是请求后正文的示例:

{"action":"do_something","id":"001"}
我举了一个简单json解析器的例子

package main

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

type some_json struct {
    Action string `json:"action"`
    Id string `json:"id"`

}

func jsonparse(rw http.ResponseWriter, request *http.Request) {
    decoder := json.NewDecoder(request.Body)

    var post_data some_json
    err := decoder.Decode(&post_data)

    if err != nil {
        panic(err)
    }


    switch ***WHAT_SHOULD_BE_HERE???*** {
    default :
      fmt.Fprintf(w,"WRONG PARAM")
    case "some_thing":
      fmt.Fprintf(w,post_data.Id + "\n\n")
            }
}

func main() {
    http.HandleFunc("/", jsonparse)
    http.ListenAndServe(":8080", nil)
}
我已经知道如何从表单值切换案例,但是
如何切换json键值的大小写?

我不确定要切换什么,但我认为您只需要删除()即可,这样操作就不再是函数调用了

小心,也许你的错误是你把字符串弄混了 在JSON中:“做点什么” 以防万一:“一些东西”

您可以将以下代码复制到游戏场

package main

import (
    "encoding/json"
    "fmt"
    "strings"
)

type some_json struct {
    Action string `json:"action"`
    Id     string `json:"id"`
}

func jsonparse() {
    r := strings.NewReader("{\"action\":\"do_something\",\"id\":\"001\"}")
    decoder := json.NewDecoder(r)

    var post_data some_json
    err := decoder.Decode(&post_data)

    if err != nil {
        panic(err)
    }

    switch post_data.Action {
    default:
        fmt.Println( "WRONG PARAM")
    case "do_something":
        fmt.Println( post_data.Id+"\n\n")
    }
}

func main() {
    jsonparse()
}

开关
接受任意值。它不关心哪个表达式计算该值。例如,
switch post_data.Action()
导致此
无法调用非函数post_data.Action(类型字符串)
这是因为
post_data.Action
不是函数。为什么在
操作
后加括号?这只是一个字段,不是一个方法。因此,使用
switch post_data.Action{
Unmarshal json映射,而不是struct,并通过键或值进行切换。