How to unmarshal an array of array in go lang

Viewed 31

payload

 "specifications": [
        ["Display", "11 Inches 120 Hz Liquid Retina Display"],
        ["Capacity", "128GB, 256GB, 512GB, 1TB, 2TB"],
        ["Chip", "Apple M1 Chip"],
        ["Front Camera", "12 MP : TrueDepth Camera, ƒ/2.4, 122 Degree Field of View, Animoji and Memoji, Lens Correction"],
        ["Rear Camera", "12 MP : Wide Camera, ƒ/1.8, Five‑Element Lens, Autofocus with Focus Pixels | 10 MP : Ultra-Wide Camera, ƒ/2.4, 125 Degree Field of View, Five‑Element Lens, Lens Correction | 12MP Telephoto Camera: ƒ/2.8 Aperture"],
        ["Sound", "Quad Speakers | AAC‑LC, HE‑AAC, HE‑AAC v2, Protected AAC, MP3, Linear PCM, Apple Lossless, FLAC, Dolby Digital (AC‑3), Dolby Digital Plus (E‑AC‑3), Dolby Atmos and Audible (formats 2, 3, 4, Audible Enhanced Audio, AAX and AAX+)"],
        ["WiFi", "IEEE 802.11a/b/g/n/ac/ax | Dual Band (2.4 GHz and 5 GHz), HT80 with MIMO"],
        ["Bluetooth", "Bluetooth 5.0"],
        ["Battery Life", "Up to 10 Hours of Surfing the Web on Wi-Fi or Watching Video, Built-in 28.65 WHr Rechargeable Battery"],
        ["Connector", "USB Type-C | 20 Watts Fast Charging, Charging Via Power Adapter or USB-C to Computer System"],
        ["Dimensions", "7.02 x 0.23 x 9.74 Inches"],
        ["Weight", "466 g"],
        ["In the Box", "1 U Tablet | Power Adapter | USB Cable | Quick Start Guide | Warranty Card"],
        ["Warranty", "12 Months | International Travellers | Carry-In"]
    ],

I did made a struct but i get following error json: cannot unmarshal array into Go struct field Product.specifications of type string

my struct

type Specifications struct {
    Item *[]string
}

product struct is

type Product struct {
    ID                  primitive.ObjectID `json:"_id" bson:"_id"`
    Product_Id          *string            `json:"user_id"`
    Category            *string            `json:"category"`
    Name                *string            `json:"name"`
    Color               *[]Color           `json:"color"`
    Size                *[]string          `json:"size"`
    Specifications      *[]string          `json:"specifications"`
    Product_Images      ProductImage       `json:"product_image"`
    Product_Accessories *[]string          `json:"product_accessories"`
    Product_Price       ProductPrice       `json:"product_price"`
}

i intend to make a api controller

func ProductCreate() gin.HandlerFunc {
    return func(c *gin.Context) {
        var payload models.Product

        var ctx, cancel = context.WithTimeout(context.Background(), 100*time.Second)
        defer cancel()

        if err := c.BindJSON(&payload); err != nil {
            c.JSON(400, gin.H{"message": locals.InternalServerError, "details": err.Error()})
            return
        }

        if _, err := productCollection.InsertOne(ctx, payload); err != nil {
            fmt.Println("User data not created")
            c.JSON(400, gin.H{"message": locals.InternalServerError})
            return
        }
        c.JSON(200, gin.H{"message": payload})
    }

}

i'm currently learning about go lang, so i might be wrong please do correct me

1 Answers

You could do something like this:

package hello
import "encoding/json"

type specification struct {
   Bluetooth string
   Capacity string
   Chip string
   Dimensions string
   Weight string
}

func (s *specification) UnmarshalJSON(b []byte) error {
   var temp [][]string
   err := json.Unmarshal(b, &temp)
   if err != nil {
      return err
   }
   s.Bluetooth = temp[0][1]
   s.Capacity = temp[1][1]
   s.Chip = temp[2][1]
   s.Dimensions = temp[3][1]
   s.Weight = temp[4][1]
   return nil
}

https://godocs.io/encoding/json#Unmarshaler

Related