How to unmarshal the json and fill into structures. Like i'm having salesorder and salesorderdetails structures. In json i will have 1 record for salesorder and multiple items for salesorderdetails structure.
Here is the go code i have tried with single item and for multiple items, but working only for single record for salesorderdetails structure.
Gocode:
package main
import (
"encoding/json"
"fmt"
)
type Order struct {
SalesId string `json:"sales_id"`
Customer string `json:"customer_name"`
TotalPrice string `json:"totalprice"`
}
type OrderDetails struct {
DetailId string `json:"detail_id"`
SalesId string `json:"sales_id"`
ItemName string `json:"item_name"`
Qty string `json:"qty"`
Price string `json:"price"`
}
type Temp struct {
Salesorder Order `json:"Salesorder"`
Salesorderdetails OrderDetails `json:"OrderDetails"`
}
func main() {
jsonByteArray := []byte(`[{"Salesorder":{"sales_id":"SOO1","customer_name":"CUST1","totalprice":"200"}, "OrderDetails":{"detailid":"1","sales_id":"SOO1","item_name":"ITEM1","qty":"2","price":"100"}}]`)
//if i use above json it is working and if i use below json its not working
//jsonByteArray := []byte(`[{"Salesorder":{"sales_id":"SOO1","customer_name":"CUST1","totalprice":"200"}, "OrderDetails":{"detailid":"1","sales_id":"SOO1","item_name":"ITEM1","qty":"2","price":"100"},{"detailid":"2","sales_id":"SOO2","item_name":"ITEM2","qty":"3","price":"200"}}]`)
var temp []Temp
err := json.Unmarshal(jsonByteArray, &temp)
if err != nil {
panic(err)
}
fmt.Printf("%+v
", temp)
fmt.Printf("%+v
", temp[0].Salesorder.SalesId)
}
Error while using multiple items:
panic: invalid character '{' looking for beginning of object key string
Output while using single item with success:
[{Salesorder:{SalesId:SOO1 Customer:CUST1 TotalPrice:200} Salesorderdetails:{SalesId:SOO1 ItemName:ITEM1 Qty:2 Price:100}}]
SOO1
Fiddle: updated with key in salesorderdetails