簡體   English   中英

使用 golang 進行 Json 編碼

[英]Json encoding with golang

resp, err := http.Get(url + t.Keywords[0] + ".json")
if err != nil {
    fmt.Println("error while getting productsRaw")
}
productsRaw, err := ioutil.ReadAll(resp.Body)
if err != nil {
    fmt.Println("error while parsing body")
}
productsRawString := string(productsRaw)
productsData := ShopifyProducts{}
json.Unmarshal([]byte(productsRawString), &productsData)
fmt.Println(productsData.Products)\

這是我從網站編碼 json 文件的代碼,如果它編碼多個產品,它就可以工作

{"product":{"id":4420737073222,"title":"W AIR MAX VERONA","body_html":"\u003cp\u003e\u003cspan\u003eDesigned with every woman in mind, the mixed-material upper features a plush collar, flashy colours and unique stitching patterns. Nike Air cushioning combines with the lifted foam heel for a modern touch, adding comfort and style to your journey.\u003c\/span\u003e\u003c\/p\u003e\n\u003cp\u003e \u003c\/p\u003e\n\u003cp\u003e\u003cspan\u003e-Smooth 

例如 Println(productsRawString) 顯示的內容,因此 url 有效,但 json.Unmarshal([]byte(productsRawString), &productsData) 不起作用。

type ShopifyProducts struct {
Products []struct {
    BodyHTML  string `json:"body_html"`
    CreatedAt string `json:"created_at"`
    Handle    string `json:"handle"`
    ID        int    `json:"id"`
    Images    []struct {
        CreatedAt  string        `json:"created_at"`
        Height     int           `json:"height"`
        ID         int           `json:"id"`
        Position   int           `json:"position"`
        ProductID  int           `json:"product_id"`
        Src        string        `json:"src"`
        UpdatedAt  string        `json:"updated_at"`
        VariantIds []interface{} `json:"variant_ids"`
        Width      int           `json:"width"`
    } `json:"images"`

Shopify 產品結構。

Unmarshal 有什么問題?

正如我在您的ShopifyProducts struct看到的,您ShopifyProducts Products聲明為array 但是在你的序列化字符串product是一個object 所以它無法解組那個原始字符串。

您還說明它在產品不止一種的情況下有效。 它在結構中的工作因為 Product 是一個數組。

可能的解決方案:

  • 預處理您的原始字符串並將您的產品綁定在一個數組中,當它不是一個數組時。 通過這種方式,您將能夠以通用方式對其進行解組。 但這將是一種解決方法,您需要編寫不必要的預處理代碼。
  • 只需更改您獲取數據的位置即可。 始終將產品保存為數組,這樣您就可以從端點發出 GET 調用,並且它始終具有通用格式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM