golang json解析的问题

hello 各位大佬,我在将json解析成结构体的过程中出现了问题

import (
   "fmt"
 jsoniter "github.com/json-iterator/go"
)
type Car struct {
   Other []byte json:"other"
}
func MyJson() {
   j := {"other": {"a":[1,2]}}
   json := jsoniter.ConfigCompatibleWithStandardLibrary
   obj := Car{}
   err := json.Unmarshal([]byte(j), &obj)
   if err != nil {
      fmt.Println(err.Error())
   } else {
      fmt.Println(obj)
   }
}

报错”main.Car.Other: base64Codec: invalid input, error found in #10 byte of ...|{"other": {"a":[1,2]|..., bigger context ...|{"other": {"a":[1,2]}}|...“

还劳烦哪位大佬给解答一下

阅读 6.7k
3 个回答
package main

import (
    "fmt"

    jsoniter "github.com/json-iterator/go"
)

type other struct {
    A []int `json:"a,omitempty"`
}

// Car 车
type Car struct {
    Other other `json:"other,omitempty"`
}

func main() {
    j := []byte(`{"other": {"a":[1,2]}}`)
    json := jsoniter.ConfigCompatibleWithStandardLibrary
    obj := Car{}
    err := json.Unmarshal(j, &obj)
    if err != nil {
        fmt.Println(err.Error())
    } else {
        fmt.Printf("%+v\n", obj)
    }
}

Go从字符串解析出结构体,是需要写明所有结构体结构的。

[]byte(j) 这什么鬼?这个操作可以直接将结构体按照 json规范 转为 字节 吗?那还需要 Marshal 函数干嘛?

  1. j 的定义会报错,这个定义肯定不对
  2. []byte 类型,在go中是做了base64编码,相应的解码的时候也需要base64解码。
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题