我正在尝试创建将输出JSON的go代码。 JSON字符串表示发票及其订单项。有两个主要部分,即标题记录和项目列表。物品清单给我带来了麻烦。它包含一组发票订单项。我不知道如何去构造它。有人可以帮我吗?
package controllers
import (
"github.com/revel/revel"
)
type Test struct {
*revel.Controller
}
type headerRecord struct {
ClientNumber string
BusinessUnit string
ValidationKey string
DataYear string
DataMonth string
TotalRevenue string
}
type dataRecord struct {
LineNumber string
InvoiceNumber string
CustomerNumber string
Zipcode string
TransDate string
Revenue string
TaxSitusRule string
TransTypeCode string
SalesTypeCode string
RegulatoryCode string
TaxExemptionCodeList []string
Geocode string
}
type request struct {
headerRecord
ItemList []dataRecord
}
func (c Test) Test() revel.Result {
request := request{
headerRecord: headerRecord{
ClientNumber: "0000000001",
BusinessUnit: "Biz Unit",
ValidationKey: "123456",
DataYear: "2016",
DataMonth: "05",
TotalRevenue: "600.00",
},
ItemList: []dataRecord{
},
}
/*
1st data record
LineNumber: "1",
InvoiceNumber: "123456",
Zipcode: "75024",
TransDate: "2016-05-15",
Revenue: "100.00",
TaxSitusRule: "05",
TransTypeCode: "050201",
SalesTypeCode: "B",
RegulatoryCode: "99",
TaxExemptionCodeList: []string{"00"},
Geocode: "",
*/
return c.RenderJSON(request)
}
这应该是输出:
{
"ClientNumber": "0000000001",
"BusinessUnit": "Biz Unit",
"ValidationKey": "12345",
"DataYear": "2016",
"DataMonth": "05",
"TotalRevenue": "600.00",
"ItemList": [
{
"LineNumber": "1",
"InvoiceNumber": "123456",
"CustomerNumber": "98765",
"BillToNumber": "",
"Zipcode": "75024",
"TransDate": "2016-05-15",
"Revenue": "100.00",
"TaxSitusRule": "05",
"TransTypeCode": "050201",
"SalesTypeCode": "B",
"RegulatoryCode": "99",
"TaxExemptionCodeList": [
"00"
],
"Geocode": ""
},
{
"LineNumber": "2",
"InvoiceNumber": "123456",
"CustomerNumber": "98765",
"BillToNumber": "",
"Zipcode": "75024",
"TransDate": "2016-05-15",
"Revenue": "200.00",
"TaxSitusRule": "05",
"TransTypeCode": "050201",
"SalesTypeCode": "B",
"RegulatoryCode": "99",
"TaxExemptionCodeList": [
"00"
],
"Geocode": ""
},
{
"LineNumber": "3",
"InvoiceNumber": "123456",
"CustomerNumber": "98765",
"BillToNumber": "",
"Zipcode": "75024",
"TransDate": "2016-05-15",
"Revenue": "300.00",
"TaxSitusRule": "05",
"TransTypeCode": "050201",
"SalesTypeCode": "B",
"RegulatoryCode": "99",
"TaxExemptionCodeList": [
"00"
],
"Geocode": ""
}
]
}
答案 0 :(得分:2)
如果要将其初始化为文字,则需要将所有逗号都放在适当的位置:
request := request{
headerRecord: headerRecord{
ClientNumber: "0000000001",
BusinessUnit: "Biz Unit",
ValidationKey: "123456",
DataYear: "2016",
DataMonth: "05",
TotalRevenue: "600.00",
},
ItemList: []dataRecord{
{
LineNumber: "1",
InvoiceNumber: "123456",
Zipcode: "75024",
TransDate: "2016-05-15",
Revenue: "100.00",
TaxSitusRule: "05",
TransTypeCode: "050201",
SalesTypeCode: "B",
RegulatoryCode: "99",
TaxExemptionCodeList: []string{"00"},
Geocode: "",
},
},
}
请参见Go Playground中的工作示例。