dongxing7318 2017-06-11 20:35
浏览 57
已采纳

试图解组地图[优先级]字符串

I have been playing around with the Golang json package, and been running into a issue, i am simply trying to unmarshal a map[string]string into map[Priority]string the easiest way, but it seems like my UnmarshalJSON isn't even running, the following is my code, i would've like to made a playground where it could run, but i am using the OS package so:

import (
    "encoding/json"
    "fmt"
    "os"
)

type Priority int

const (
    VERYLOW = Priority(iota)
    LOW
    MEDIUM
    HIGH
    VERYHIGH
)

const (
    verylow  = "verylow"
    low      = "low"
    medium   = "medium"
    high     = "high"
    veryhigh = "veryhigh"

    // ANSI color constants.
    RESET      = "\x1b[0m"
    BRIGHT     = "\x1b[1m"
    DIM        = "\x1b[2m"
    UNDERSCORE = "\x1b[4m"
    BLINK      = "\x1b[5m"
    REVERSE    = "\x1b[7m"
    HIDDEN     = "\x1b[8m"
    FGBLACK    = "\x1b[30m"
    FGRED      = "\x1b[31m"
    FGGREEN    = "\x1b[32m"
    FGYELLOW   = "\x1b[33m"
    FGBLUE     = "\x1b[34m"
    FGMAGENTA  = "\x1b[35m"
    FGCYAN     = "\x1b[36m"
    FGWHITE    = "\x1b[37m"
    BGBLACK    = "\x1b[40m"
    BGRED      = "\x1b[41m"
    BGGREEN    = "\x1b[42m"
    BGYELLOW   = "\x1b[43m"
    BGBLUE     = "\x1b[44m"
    BGMAGENTA  = "\x1b[45m"
    BGCYAN     = "\x1b[46m"
    BGWHITE    = "\x1b[47m"

    TITLE_COLOUR = BRIGHT + FGGREEN
    NUMBER_COLOR = FGGREEN

    //color constants
    BLACK         = "BLACK"
    RED           = "RED"
    GREEN         = "GREEN"
    YELLOW        = "YELLOW"
    BLUE          = "BLUE"
    MAGENTA       = "MAGENTA"
    CYAN          = "CYAN"
    WHITE         = "WHITE"
    BRIGHTBLACK   = "BRIGHTBLACK"
    BRIGHTRED     = "BRIGHTRED"
    BRIGHTGREEN   = "BRIGHTGREEN"
    BRIGHTYELLOW  = "BRIGHTYELLOW"
    BRIGHTBLUE    = "BRIGHTBLUE"
    BRIGHTMAGENTA = "BRIGHTMAGENTA"
    BRIGHTCYAN    = "BRIGHTCYAN"
    BRIGHTWHITE   = "BRIGHTWHITE"
    NOCOLOR       = ""
)

type Config struct {
    Name     string
    FGColors map[Priority]string
}

type MarshalableConfig struct {
    Name     string
    FGColors map[string]string
}

var priorityMapFromString = map[string]Priority{
    veryhigh: VERYHIGH,
    high:     HIGH,
    medium:   MEDIUM,
    low:      LOW,
    verylow:  VERYLOW,
}

var priorityToString = map[Priority]string{
    VERYHIGH: veryhigh,
    HIGH:     high,
    MEDIUM:   medium,
    VERYLOW:  verylow,
    LOW:      low,
}

func (p Priority) String() string {
    return priorityToString[p]
}

func PriorityFromString(priority string) Priority {
    if p, ok := priorityMapFromString[priority]; ok {
        return p
    }
    return MEDIUM
}

func (priority *Priority) UnmarshalJSON(data []byte) error {
    var s string
    if err := json.Unmarshal(data, &s); err != nil {
        return err
    }
    *priority = PriorityFromString(s)
    return nil
}

func main() {
    fgColors := map[string]string{
        verylow:  RED,
        low:      BLUE,
        medium:   GREEN,
        high:     BRIGHTBLUE,
        veryhigh: BRIGHTMAGENTA,
    }

    m := MarshalableConfig{"Alice", fgColors}
    b, err := json.Marshal(m)
    if err != nil {
        panic(err)
    }
    file, err := os.Create("testfile.json")
    if err != nil {
        panic(err)
    }
    file.Write(b)

    emptyConfig := Config{}
    err = json.Unmarshal(b, &emptyConfig)
    if err != nil {
        fmt.Printf("Got a error from unmarshalling: %+v 
", err)
        panic(err)
    }
    fmt.Printf("%+v 
", emptyConfig)
    var x interface{} = emptyConfig.FGColors[VERYHIGH]
    fmt.Println(x.(string))

}

I get the error:

json: cannot unmarshal number high into Go value of type main.Priority  

So the impression i get is that it never calls my UnmarshalJSON method on the priority, and i don't know if thats the way its suppose to work anyway now that i have nested the Priority type inside of the map.

So i thouth maybe i have to do a alias type for the whole map like:

type FGColor map[Priority]string 

and implement unmarshal on that instead, but that doesn't seem logical, because nested structs would be a nightmare to unmarshal i would think.

What am i doing wrong??

  • 写回答

2条回答 默认 最新

  • dongnai5905 2017-06-14 22:19
    关注

    I updated my code, as per the comment from @AniSkywalker to the following code, using the UnmarshalText:

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type Priority int
    
    const (
        VERYLOW = Priority(iota)
        LOW
        MEDIUM
        HIGH
        VERYHIGH
    )
    
    const (
        verylow  = "verylow"
        low      = "low"
        medium   = "medium"
        high     = "high"
        veryhigh = "veryhigh"
    
        // ANSI color constants.
        RESET      = "\x1b[0m"
        BRIGHT     = "\x1b[1m"
        DIM        = "\x1b[2m"
        UNDERSCORE = "\x1b[4m"
        BLINK      = "\x1b[5m"
        REVERSE    = "\x1b[7m"
        HIDDEN     = "\x1b[8m"
        FGBLACK    = "\x1b[30m"
        FGRED      = "\x1b[31m"
        FGGREEN    = "\x1b[32m"
        FGYELLOW   = "\x1b[33m"
        FGBLUE     = "\x1b[34m"
        FGMAGENTA  = "\x1b[35m"
        FGCYAN     = "\x1b[36m"
        FGWHITE    = "\x1b[37m"
        BGBLACK    = "\x1b[40m"
        BGRED      = "\x1b[41m"
        BGGREEN    = "\x1b[42m"
        BGYELLOW   = "\x1b[43m"
        BGBLUE     = "\x1b[44m"
        BGMAGENTA  = "\x1b[45m"
        BGCYAN     = "\x1b[46m"
        BGWHITE    = "\x1b[47m"
    
        TITLE_COLOUR = BRIGHT + FGGREEN
        NUMBER_COLOR = FGGREEN
    
        //color constants
        BLACK         = "BLACK"
        RED           = "RED"
        GREEN         = "GREEN"
        YELLOW        = "YELLOW"
        BLUE          = "BLUE"
        MAGENTA       = "MAGENTA"
        CYAN          = "CYAN"
        WHITE         = "WHITE"
        BRIGHTBLACK   = "BRIGHTBLACK"
        BRIGHTRED     = "BRIGHTRED"
        BRIGHTGREEN   = "BRIGHTGREEN"
        BRIGHTYELLOW  = "BRIGHTYELLOW"
        BRIGHTBLUE    = "BRIGHTBLUE"
        BRIGHTMAGENTA = "BRIGHTMAGENTA"
        BRIGHTCYAN    = "BRIGHTCYAN"
        BRIGHTWHITE   = "BRIGHTWHITE"
        NOCOLOR       = ""
    )
    
    type Config struct {
        Name     string
        FGColors map[Priority]string
    }
    
    type MarshalableConfig struct {
        Name     string
        FGColors map[string]string
    }
    
    var priorityMapFromString = map[string]Priority{
        veryhigh: VERYHIGH,
        high:     HIGH,
        medium:   MEDIUM,
        low:      LOW,
        verylow:  VERYLOW,
    }
    
    var priorityToString = map[Priority]string{
        VERYHIGH: veryhigh,
        HIGH:     high,
        MEDIUM:   medium,
        VERYLOW:  verylow,
        LOW:      low,
    }
    
    func (p Priority) String() string {
        return priorityToString[p]
    }
    
    func PriorityFromString(priority string) Priority {
        if p, ok := priorityMapFromString[priority]; ok {
            return p
        }
        return MEDIUM
    }
    
    func (priority *Priority) UnmarshalText(data []byte) error {
        *priority = PriorityFromString(string(data))
        return nil
    }
    
    func main() {
        fgColors := map[string]string{
            verylow:  RED,
            low:      BLUE,
            medium:   GREEN,
            high:     BRIGHTBLUE,
            veryhigh: BRIGHTMAGENTA,
        }
    
        m := MarshalableConfig{"Alice", fgColors}
        b, err := json.Marshal(m)
        if err != nil {
            panic(err)
        }
    
        emptyConfig := Config{}
        err = json.Unmarshal(b, &emptyConfig)
        if err != nil {
            fmt.Printf("Got a error from unmarshalling: %+v 
    ", err)
            panic(err)
        }
        fmt.Printf("%+v 
    ", emptyConfig)
        var x interface{} = emptyConfig.FGColors[VERYHIGH]
        fmt.Println(x.(string))
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。