问题描述
我想解组一些JSON,其中的一部分包含定义为Spaces
的{{1}}类型的字段。为了使这项工作有效,我为上述类型实现了type Spaces map[rune]float32
,首先宽容地将其编组为UnmarshalJSON([]byte) error
,然后仅接受键长度恰好为1个符文的键/值对。>
但是,当调用map[string]float32
类型的UnmarshalJSON()
时,接收者Spaces
为nil。为什么?
s
解组功能:
type FontLoadInfo struct {
FontMetrics
Atlases []*AtlasLoadInfo
}
type FontMetrics struct {
BaseKerning float32
KerningOffsets map[string]float32
Spaces Spaces
LineBreakYdistance float32
}
type AtlasLoadInfo struct {
TextureFilePath string
BaseLineY int
HeightAboveBaseLine int
HeightBelowBaseLine int
distanceBetweenBaseLines int
MinBlankPixelColumns int
Lines []string
}
type Spaces map[rune]float32
func (s Spaces) UnmarshalJSON(b []byte) error {
if string(b) == "null" {
return nil
}
var compliantMap map[string]float32
err := json.Unmarshal(b,&compliantMap)
if err != nil {
return err
}
for k,v := range compliantMap {
if utf8.RuneCountInString(k) != 1 {
return fmt.Errorf("none or multiple runes in key")
}
r,_ := utf8.DecodeRuneInString(k)
if r == utf8.RuneError {
return fmt.Errorf("invalid encoding in key")
}
s[r] = v // s is nil
}
return nil
}
我要解组的JSON:
func ReadFontLoadInfo(filePath string) (*FontLoadInfo,error) {
data,err := IoUtil.ReadFile(filePath)
if err != nil {
return nil,fmt.Errorf("Could not read font load info file: %w",err)
}
var fontLoadInfo *FontLoadInfo
err = json.Unmarshal(data,&fontLoadInfo)
if err != nil {
return nil,fmt.Errorf("Could not unmarshal font load info: %w",err)
}
return fontLoadInfo,nil
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)