解组到 map[string]interface{} 后对 ma[string][]string 的类型断言失败

type assertion to ma[string][]string after unmarshaling to map[string]interface{} fails

解组为 map[string]interface{} 后无法断言类型 map[string][]stringHere 是重现问题的小片段:

package main

import (
    "encoding/json"
    "fmt"
)

type Test struct {
    M map[string][]string `json:"m"`
}

func main() {
    b := []byte(`{"m":{}}`) //m will always exist but it might be empty or have some values. No difference if me is not empty, e.g. `{"m":{"s": ["abc"]}}`

    var test Test
    json.Unmarshal(b, &test) // This is fine, but for some reason I have to unmarshal to map[string]interface{}
    fmt.Println(test)

    var raw map[string]interface{}
    json.Unmarshal(b, &raw)
    test2 := Test{}
    test2.M = raw["m"].(map[string][]string) // error here
    fmt.Println(test2)
}

我收到这个错误:

interface {} is map[string]interface {}, not map[string][]string

当您将 json 解组为接口{}时,结果是一棵树,其组成如下:

  • map[string]interface{} 用于 json 个对象,
  • []interface{} 用于 json 数组,
  • string、float64、bool、json.Number 或值 nil。

解组后。 raw["m"]是一个map[string]interface{},其值为[]interface{}。然后你可以断言每个值到字符串:

for k,v:= range raw["m"].(map[string]interface{}) {
   for _,x:=range v.([]interface{}); {
      test2.M[k]=append(test2.M[k],x.(string))
   }
}