doufeikuang7724 2017-11-07 19:47
浏览 45
已采纳

如何解组json并填充到golang中的结构

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

https://play.golang.org/p/klIAoNi18r

  • 写回答

2条回答 默认 最新

  • dongpai9986 2017-11-07 20:04
    关注

    Try this:

    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 {
        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":[{"sales_id":"SOO1","item_name":"ITEM1","qty":"2","price":"100"},{"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)
    
        // Printing all Orders with some details
        for _, order := range temp {
            fmt.Println("Customer:", order.Salesorder.Customer)
    
            for _, details := range order.Salesorderdetails {
                fmt.Printf("    ItemName: %s, Price: %s
    ", details.ItemName, details.Price)
            }
        }
    }
    

    .. OrderDetails is an array now

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程