猿问

无法在 golang 中正确解组数据从映射到结构

我目前无法将数据从地图正确解组到结构中。以下是代码片段(操场上的简短代码):


请您提供在解组回数据时获取默认值的原因。


package main


import (

    "fmt"

    "encoding/json"

    "os"

    )


func main() {

    fmt.Println("Hello, playground")

    type PDPOffer struct {

        cart_value            int    `json:"cart_value"`

        discount_amount_default int    `json:"discount_amount_default"`

        max_discount           string `json:"max_discount"`

        }


        a:= map[string]interface{} {

        "cart_value"              : 1,

        "max_discount"            : 2,

        }

        var pdf PDPOffer

        b, err := json.Marshal(a)

        if err != nil {

            fmt.Println("error:", err)

        }

        os.Stdout.Write(b)//working

        err1 := json.Unmarshal(b, &pdf)

        if err1 != nil {

            fmt.Println("error:", err)

        }

        fmt.Printf("%+v", pdf)//displaying just the defualt values????????

}


隔江千里
浏览 295回答 3
3回答

jeck猫

此外,您试图将一个 int 值编组为“max_discount”的字符串,您需要将其作为字符串存储在您要编组的地图中:a := map[string]interface{}{    "cart_value":   1,    "max_discount": "2",}错误处理有一个错误检查err1 != nil然后打印err隐藏消息error: json: cannot unmarshal number into Go value of type string所有修复的工作示例:http : //play.golang.org/p/L8VC-531nS

冉冉说

解组不起作用的原因是您需要公开结构的字段,为此您需要以大写字母开头的字段名称。有以下内容:type PDPOffer struct {        Cart_value            int    `json:"cart_value"`        Discount_amount_default int    `json:"discount_amount_default"`        Max_discount           string `json:"max_discount"`        }

潇潇雨雨

json.Marshal并且json.Unmarshal只能处理导出的结构字段。您的字段不会导出,对 json 代码不可见。
随时随地看视频慕课网APP

相关分类

Go
我要回答