简体   繁体   English

json:无法将 object 解组为 Go 类型值

[英]json: cannot unmarshal object into Go value of type

I can't decode the json code below... any ideas why it doesn't work?我无法解码下面的 json 代码……知道为什么它不起作用吗? See also play.golang另见play.golang

package main
    
import (
    "encoding/json"         
)
    
type LocationReadable struct {
    District string
    City     string
    State    string
}
    
type Locale struct {
    Location         string
    CountryCode      string
    CurrencyId       string
    CurrencySymbol   string
    LocationReadable LocationReadable
}
    
type Media struct {
    Image string
    Video string
}
    
type Variations struct {
    FixedPrice float64
    Media      Media
    Quantity   int
}
    
type PaymentData struct {
    PaymentName    string
    PaymentService string
}
    
type Payment struct {
    Online  PaymentData
    Offline PaymentData
}
    
type Shipping struct {
    ShippingService        string
    ShippingName           string
    ShippingCost           float64
    HandlingTimeMax        int
    DispatchTimeMin        int
    DispatchTimeMax        int
    ShippingAdditionalCost int
}

type Item []struct {
    _version    string
    CategoryId  string
    Title       string
    Media       Media
    SellerId    string
    Locale      Locale
    ListingType string
    Payment     Payment
    StartTime   string
    EndTime     string
    Shipping    Shipping
    TitleSlug   string
    Variations  Variations
    _fpaiStatus string
}

func main() {
    itemInfoR := `{"locale":{"location":"51.51121389999999,-0.11982439999997041","countryCode":"GB","currencyId":"GBP","currencySymbol":"£","locationReadable":{"district":"City of Westminster","city":"London","state":"Greater London"}},"_version":"serving","categoryId":["Root","Cameras \u0026 Photo","Digital Cameras"],"title":"many pictures","media":{"image":["//lh5.ggpht.com/O_o_N6CFkClY5AV0-LqntpyFjor7Of4u23ZcK7lYwc2uY1ea7GWi61VDJZCB7UCb79svkjKPHIenqwEUhjHi0jdIQnnl6z_p03yktPUB1FBHezIQ","//lh6.ggpht.com/ih3q2d7CenGLPyupH9FpfsoJQWQpw1i8wWA2Kd26bFnSF2fbnKyGU9WePIhCgEeqw5p6YMVmFi1c9oS0Ag93aF_oZ3ZiwK7fQuSYIrZ9VhgXbrTHkw","//lh6.ggpht.com/7RJRsapsnwWL3_KiLIjMz4QojDzUvsztXtvKTFvIfde_AHcc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eqAP379XB9O1d0BWPanhr-MguzKxfHeUvYTs6yHzDkxyfe0NA","//lh4.ggpht.com/7aofqklSkF3AMDfF19yqsA9J3EfEiKy1NdOelEGKNnW0Cv5tGEpq2PF_jZO1MVoBbrrmVVRv0Tdq7I8KyZbIlyHdbTs1jMl7dEFqVMvsPcyaORyHlQ","//lh4.ggpht.com/anYJHqkMCkuhmIHQTBspLtWcDTyx1ZRe84_q5pAgVEOVmsKkaKhS725N4YFoj2zpJrBP7iTC2vf1GUtrp6H7kkm8c1k6zkW6I_Gf5f9A3re_I8Ex","//lh3.ggpht.com/OtSw0rU-DvfoXgoWrQdkln6Kz7O14TF9qrPNJSGJnZLeDqUEctOn1DT09pdwwVpNQV-cXmVYQL-PX4XPhpZLWH1ciSkVT6WHNmTz1D9pHphBwJUv","//lh3.ggpht.com/cTCZnXPIjI-EO2bvQdLgeoSLOSlMFcv805n347Zyci9XDYUdcVDC_5H7SFVYDr4pC5HtQDYnrOHL6AinLW7hWtfSCLlvVhVUNQ-DlDn0NwZ-1iCO-g","//lh4.ggpht.com/i-mL_JcF9rwjQq6HnuKzuAHU41_UGxQ62IOPZvaDrATXaPFbhe-EbT7ZIpboyNA5PXRCsxNsZ9hu58edRvNs5ScgKN8Lg-00J2LhlwMAbdEsv7b0nw","//lh6.ggpht.com/D_YV2BG1WWwl67xNloP3sxzRkqhcVTgJi58L-A8nLrOcMR_tBqLz4fHEGQ-qiNcG_-32MNy3dlSPWrTBKzBcweJxgMnRVet5yuGfelUlwehDtXX_3w"],"video":[]},"sellerId":"mihai","listingType":"fixedPrice","payment":{"online":[{"paymentName":"PayPal","paymentService":"paypal"}],"offline":[{"paymentName":"Pay on Pick-up","paymentService":"payOnPickup"}]},"startTime":"2014-01-04T10:02:18+00:00","endTime":"2014-04-04T10:02:18+00:00","shipping":[{"shippingService":"economy","shippingName":"Economy","shippingCost":1.0,"handlingTimeMax":4,"dispatchTimeMin":1,"dispatchTimeMax":10,"shippingAdditionalCost":"2"},{"shippingService":"localPickup","shippingName":"Local Pick-Up","shippingCost":0.0,"handlingTimeMax":2,"dispatchTimeMin":0,"dispatchTimeMax":0,"shippingAdditionalCost":"0"}],"titleSlug":"many-pictures","variations":[{"fixedPrice":222999.0,"media":{"image":["//lh6.ggpht.com/ih3q2d7CenGLPyupH9FpfsoJQWQpw1i8wWA2Kd26bFnSF2fbnKyGU9WePIhCgEeqw5p6YMVmFi1c9oS0Ag93aF_oZ3ZiwK7fQuSYIrZ9VhgXbrTHkw","//lh6.ggpht.com/9aXLmPRVeZnxkwvNb3mWTF8kvfEY_lho_lOVVc9AbNqLb8GQmiS_XXVZ3OKqMv2pxgYSayMYPPRh6ACYyh0H8KtS8mPD6MKUkEajwxkTtp5Q4Lo","//lh3.ggpht.com/FG_QXZPHJ2tTYwI_t5Fg1KqivglVg9RlJn0JRsu9Ox8vJ7IcBirb2IV_I1LL_WVOMxfTuBBSDLMlrw9v0MCAdmnPCR29sCbRGjhm6zEfIH-3q2QSdw"],"video":[]},"quantity":1121,"Brand":"Bell \u0026 Howell"},{"fixedPrice":211.0,"media":{"image":["//lh6.ggpht.com/qAtjgyHAB734Ox_4NC_fa-ZRqrCjCmJu0Tp8bo-HMO88duv8l4hhuv2REBkB--yneFzOL7annecVlGty-YsKouondiOFVnAZWzjpdrfsGfbL6wh2","//lh3.ggpht.com/FG_QXZPHJ2tTYwI_t5Fg1KqivglVg9RlJn0JRsu9Ox8vJ7IcBirb2IV_I1LL_WVOMxfTuBBSDLMlrw9v0MCAdmnPCR29sCbRGjhm6zEfIH-3q2QSdw","//lh6.ggpht.com/9aXLmPRVeZnxkwvNb3mWTF8kvfEY_lho_lOVVc9AbNqLb8GQmiS_XXVZ3OKqMv2pxgYSayMYPPRh6ACYyh0H8KtS8mPD6MKUkEajwxkTtp5Q4Lo","//lh3.ggpht.com/MOrI-zKNMNrQE_aHj5hzbojP3T0hEMJKK6K8UO3e1NBC-nkcQeIM1QnvtJdT_G-W4e7-qv4BiqwdWcNHBpZXOmmX3tcuYEV8u_ANEoa9_aUIfeyg"],"video":[]},"quantity":2,"Brand":"Fujifilm"},{"fixedPrice":22.0,"media":{"image":["//lh3.ggpht.com/jgOebMihBoIZvHE4EOklJvZ_k-9egjNIlUKfKFcLkvXJs8g2FXjPvdFUbwqGrkHrMtyis8uOvgt-E51Vm11hq4bieh7h0cegca0VI4vFtFaAemU","//lh3.ggpht.com/MOrI-zKNMNrQE_aHj5hzbojP3T0hEMJKK6K8UO3e1NBC-nkcQeIM1QnvtJdT_G-W4e7-qv4BiqwdWcNHBpZXOmmX3tcuYEV8u_ANEoa9_aUIfeyg","//lh4.ggpht.com/anYJHqkMCkuhmIHQTBspLtWcDTyx1ZRe84_q5pAgVEOVmsKkaKhS725N4YFoj2zpJrBP7iTC2vf1GUtrp6H7kkm8c1k6zkW6I_Gf5f9A3re_I8Ex"],"video":[]},"quantity":12,"Brand":"Gateway"}],"_fpaiStatus":"published"}`
    itemInfoBytes := []byte(itemInfoR)
    var ItemInfo Item
    er := json.Unmarshal(itemInfoBytes, &ItemInfo)
    if er != nil {
        panic(er)
    }
        
}

Here's a fixed version of it: http://play.golang.org/p/w2ZcOzGHKR 这是它的固定版本: http//play.golang.org/p/w2ZcOzGHKR

The biggest fix that was needed is when Unmarshalling an array, that property needs to be an array/slice in the struct as well. 需要解决的最大修复是解组数组时,该属性也需要是结构中的数组/切片。

For example: 例如:

{ "things": ["a", "b", "c"] }

Would Unmarshal into a: Unmarshal将成为:

type Item struct {
    Things []string
}

And not into: 不是

type Item struct {
    Things string
}

The other thing to watch out for when Unmarshaling is that the types line up exactly. 另一件需要注意的事情就是Unmarshaling,它们的类型完全排列在一起。 It will fail when Unmarshalling a JSON string representation of a number into an int or float field -- "1" needs to Unmarshal into a string , not into an int like we saw with ShippingAdditionalCost int 解组数的JSON字符串表示到时它会失败intfloat场- "1"需要解组为一个string ,而不是插入int如与我们看到ShippingAdditionalCost int

Determining of root cause is not an issue since Go 1.8; 从Go 1.8开始,确定根本原因不是问题; field name now is shown in the error message: 字段名称现在显示在错误消息中:

json: cannot unmarshal object into Go struct field Comment.author of type string

You JSON doesn't match your struct fields: Eg "district" in JSON and "District" as the field. 您的JSON与您的结构字段不匹配:例如JSON中的“district”和字段中的“District”。

Also: Your Item is a slice type but your JSON is a dict value. 另外:你的Item是一个切片类型,但你的JSON是一个dict值。 Do not mix this up. 不要混淆了。 Slices decode from arrays. 切片从数组解码。

Just in case you're looking for an answer to this from an AWS perspective, particularly if you're trying to use UnmarshalListOfMaps() on the items coming back from a DynamoDB query() , then watch out for a simple typo I made.以防万一您正在从 AWS 的角度寻找此问题的答案,尤其是当您尝试对从 DynamoDB query()返回的项目使用UnmarshalListOfMaps()时,请注意我犯的一个简单错字。

Given that this function UnmarshalListOfMaps() takes in...a list of maps:-) then it needs to unmarshal into a List of whatever struct you're trying to build, and not just the plain struct itself.鉴于此 function UnmarshalListOfMaps()接收...一个映射列表:-) 然后它需要解组为一个List ,其中包含您要构建的任何struct ,而不仅仅是普通结构本身。 This was throwing me off because I was trying to start by querying for something that should only return one row.这让我失望了,因为我试图从查询应该只返回一行的东西开始。

movie := Movie{}
// Run the DynamoDB query
resp, err := session.Query(input)  // type QueryInput
if err != nil {
    log.WithError(err).Error("Error running DynamoDB query")
}
// Unmarshal all the attribute values into a Movie struct
err = dynamodbattribute.UnmarshalListOfMaps(resp.Items, &movie); if err != nil {
    log.WithError(err).Error("Error marshaling DynamoDB result into Movie")
    return link, err
}

The problem is in the first line.问题出在第一行。 It should be movies:= []Movie{} and then the reference &movie needs to change to &movies as well.它应该是movies:= []Movie{}然后引用&movie也需要更改为&movies If you leave it just as it is above, then the AWS Go SDK will throw this error:如果你像上面那样保留它,那么 AWS Go SDK 将抛出这个错误:

cannot unmarshal list into Go value of type (etc).

If you ever face this while typing yml file not copy-pasting, it might be a problem with your yml file - mine was wrong indent.如果您在键入 yml 文件而不是复制粘贴时遇到此问题,则可能是您的 yml 文件有问题 - 我的缩进错误。 This happened while making pipeline on concourse.这是在大厅制作管道时发生的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 json:无法将对象解组为Auction.Item类型的Go值 - json: cannot unmarshal object into Go value of type Auction.Item json:无法将 object 解组为 []*main.Config 类型的 Go 值 - json: cannot unmarshal object into Go value of type []*main.Config json 错误,无法将对象解组为 Go 值 - json error, cannot unmarshal object into Go value 如何修复 json:无法将 object 解组为 []json.RawMessage 类型的 Go 值 - How to fix json: cannot unmarshal object into Go value of type []json.RawMessage 用golang解析Json文件,遇到问题“cannot unmarshal object into Go value of type” - Parse a Json file with golang, encountering a problem “cannot unmarshal object into Go value of type” oc 补丁替换图像名称错误“json:无法将 object 解组为 Go 类型的 jsonpatch.Patch 值” - oc patch replace image name error " json: cannot unmarshal object into Go value of type jsonpatch.Patch" json:无法将字符串解组为[] main.KVU类型的Go值 - json: cannot unmarshal string into Go value of type []main.KVU json:无法将字符串解组为 map[string]interface {} 类型的 Go 值 - json: cannot unmarshal string into Go value of type map[string]interface {} json:无法将数组解组为main类型的Go值 - json: cannot unmarshal array into Go value of type main.Posts json:无法将字符串解组为 MyMap.map 类型的 Go 值 - json: cannot unmarshal string into Go value of type MyMap.map
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM