User Tools

Site Tools


unm.go
/*
 * Author, Copyright: Oleg Borodin <onborodin@gmail.com>
 */
package main
 
import (
    "encoding/json"
    "fmt"
)
 
type Request struct {
    Invoices Invoices   `json:"invoice"`
}
 
type Invoice struct {
    InvoiceUID  string  `json:"invoiceUID"`
}
 
type Invoices struct {
    Payload []Invoice
}
 
func (this Invoices) MarshalJSON() ([]byte, error) {
    json, err := json.Marshal(this.Payload)
    return json, err
}
 
func (this *Invoices) UnmarshalJSON(data []byte) error {
    this.Payload = make([]Invoice, 0)
 
    var invoice Invoice
    err := json.Unmarshal(data, &invoice)
    if err == nil {
        this.Payload = append(this.Payload, invoice)
        return nil
    }
    invoices := make([]Invoice, 0)
    err = json.Unmarshal(data, &invoices)
    if err == nil {
        this.Payload = invoices
        return nil
    }
    return err
}
 
func main() {
 
    {
        j := []byte(`{ "invoice": [ { "invoiceUID": "0000-0001" }, {"invoiceUID": "0000-0002" } ] }`)
        var i Request
        err := json.Unmarshal(j, &i)
        if err != nil {
            fmt.Println(err)
            return
        }
        j, err = json.MarshalIndent(i, "", "    ")
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Println(string(j))
    }
 
    {
        j := []byte(`{ "invoice": { "invoiceUID": "0000-0001" } }`)
        var i Request
        err := json.Unmarshal(j, &i)
        if err != nil {
            fmt.Println(err)
            return
        }
        j, err = json.MarshalIndent(i, "", "    ")
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Println(string(j))
    }
}
$ go run invoice_map_v3.go
{
    "invoice": [
        {
            "invoiceUID": "0000-0001"
        },
        {
            "invoiceUID": "0000-0002"
        }
    ]
}
{
    "invoice": [
        {
            "invoiceUID": "0000-0001"
        }
    ]
}