gocarina / gocsv

The GoCSV package aims to provide easy CSV serialization and deserialization to the golang programming language
MIT License
1.99k stars 245 forks source link

new version can't work well #227

Open tooodooo opened 2 years ago

tooodooo commented 2 years ago

csv:

id,key,items,radio,upgrade
1,"{""items"":21000041,""count"":1}","[{""items"":20000000,""count"":88,""pro"":400}]","[20000000,21000091,21000062,21000092,20000032,20000007,21000093,21000202,21000094,20000033]",30

go struct:

type ItemBase struct {
    Items            uint32
    Count            uint32
    RandomAttributes string
    Quality          uint32
}

type ItemBaseWeight struct {
    Items uint32
    Count uint32
    Pro   uint32
}

type AdventureBoxConf struct {
    Id        uint32                  `csv:"id"`
    Key       *model.ItemBase         `csv:"key"`
    Items     []*model.ItemBaseWeight `csv:"items"`
    Broadcast []uint32                `csv:"radio"`
    Upgrade   uint32                  `csv:"upgrade"`
}

with this version: github.com/gocarina/gocsv v0.0.0-20220823132111-71f3a5cb2654 work well. but github.com/gocarina/gocsv v0.0.0-20221105105431-c8ef78125b99 can not work. AdventureBoxConf.Key is nil.

Maybe the CSV format is not rigorous enough?

acls commented 2 years ago

Have you tried adding a custom unmarshaler for ItemBase? eg:

import "encoding/json"

func (i *ItemBase) UnmarshalCSV(csv string) error {
    return json.Unmarshal([]byte(csv), i)
}

This may not be useful to you, since I couldn't find a previous version that marshaled to that format. My guess is that the csv is coming from somewhere else. But if you also wanted to output you would also need a custom marshaler and add json struct tags. eg:

type ItemBase struct {
    Items            uint32 `json:"items"`
    Count            uint32 `json:"count"`
    RandomAttributes string `json:"randomAttributes,omitempty"`
    Quality          uint32 `json:"quality,omitempty"`
}

func (i *ItemBase) MarshalCSV() (string, error) {
    b, err := json.Marshal(i)
    return string(b), err
}