首页 > [Go] 如何将interface{} 转成struct数组?

[Go] 如何将interface{} 转成struct数组?

想将请求回来的JSON数据用go-simplejson转换成interface{} 转成对应的struct数组,本来想先marshal后再unmarshal到struct里,但是请求回来的数据有些字段有些情况是不存在,marshal会将不存在的字段以零值添加,导致不能正常使用,想跳过marshal和unmarshal的过程,直接将map转成struct,应该如何做?

具体化一下:

type Foo struct {
    Name String `json:"name"`
    Skill  struct {
        Title String `json:"title"`
        Count Int `json:"count"`
        Level Int `json:"level"`
    } `json:"skill"`
    Description  string `json:"description"`
}
{"Name":"Ken", [{ "Title": "AAA", "Count": "2" ,Level: "1"}, { "Title": "BBB", "Count": "5" }], "Description": "AAA"}

服务器有时候会忽略没有数据的字段,这时候用unmarshal的话,被忽略的字段会以zero-value的方式出现,导致我这边的判断出现问题。

是否可以对JSON解析是修改成自己想要的赋初始值呢?


marshal并不会将不存在的字段以零值添加,而是这个字段默认就是零值


描述有点乱,不是看得很明白。如果只是想要将一个map转换成struct的话,用reflect很容易的。
https://github.com/issue9/conv/blob/master/obj.go#L75 这个是简单的示例。


你可以考虑先初始化你的struct,然后在做Unmarshal。

https://play.golang.org/p/y1z41DfYRT

package main

import (
    "fmt"
    "encoding/json"
)

func main() {
    var data = struct {
        Int int
        Int2 int
    } {
        Int: -1,
    }
    err := json.Unmarshal([]byte("{\"Int2\": 10}"), &data)
    if err != nil {
        panic(err)
    }
    fmt.Println("data.Int  = ", data.Int)
    fmt.Println("data.Int2 = ", data.Int2)
}
【热门文章】
【热门文章】