skip to Main Content

I had meet A Json Unmarshal Situation

type Item struct {
Price int64 `json:"price"`
Id    int64 `json:"id"`
}



import (
json "project/pkg/utils/json"
)


func HandleJsonData() {

   jsonData := []byte(`[{"id":"1000,"price":"30"},{"id":"1001,"price":50}]`)

   var item Item
   err = json.Unmarshal(jsonData, &item)
   if err != nil {
      fmt.Println(err)
   }

}

I cannot direct urmarshal jsondata correctly.
How to solve this situation

2

Answers


  1. Chosen as BEST ANSWER
    type Item struct {
       Price json.Number `json:"price"`
       Id    int64 `json:"id"`
    }
    
    func HandleJsonData() {
    
       jsonData := []byte(`[{"id":"1000,"price":"30"},{"id":"1001,"price":50}]`)
    
       var item Item
       err = json.Unmarshal(jsonData, &item)
       if err != nil {
          fmt.Println(err)
       }
    
       price, _ := strconv.ParseInt(string(item.Price), 10, 64)
    }
    

  2. Working code:

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type Item struct {
        ID    string `json:"id"`
        Price int    `json:"price"`
    }
    
    func main() {
        jsonData := []byte(`[{"id":"1000","price":30},{"id":"1001","price":50}]`)
    
        var items []Item
        err := json.Unmarshal(jsonData, &items)
        if err != nil {
            panic(err)
        }
    
        fmt.Println(items)
    }
    

    json.Unmarshal function to decode the JSON data into a slice of Item structs. The &items argument to json.Unmarshal is a pointer to the slice variable items, which allows the json package to modify the slice directly.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search