jaypipes / ghw

Go HardWare discovery/inspection library
Apache License 2.0
1.62k stars 174 forks source link

cannot unmarshal string into Go struct field Disk.Blocks.disks.drive_type of type block.DriveType #274

Closed Techno-Fox closed 2 years ago

Techno-Fox commented 3 years ago

I was trying to marshal and unmarshal data, but then this comes up. I believe it's because DriveType is an int, while the marshaled version is a string, because of the MarshalJSON function converting it to a string.

Proposal: Add an UnmarshalJSON function to types that are converted from the original. To be converted back their original type for unmarshaling.

Please correct me if I'm wrong!

ffromani commented 2 years ago

Hi! could you please provide a simple reproducer to fully understand the flow?

Techno-Fox commented 2 years ago

package main

import (
    "encoding/json"
    "log"

    "github.com/jaypipes/ghw"
)

func main() {
    blocks, err := ghw.Block(ghw.WithDisableWarnings())
    if err != nil {
        log.Fatal(err)
    }

    data, err := json.Marshal(blocks)
    if err != nil {
        log.Fatal(err)
    }

    var bi *ghw.BlockInfo
    err = json.Unmarshal(data, &bi)
    if err != nil {
        log.Fatal(err)
    }
}
ffromani commented 2 years ago

thanks @Techno-Fox ! working on a fix