Partly JSON unmarshal into a map in Go

前端 未结 3 1826
一向
一向 2020-11-29 15:34

My websocket server will receive and unmarshal JSON data. This data will always be wrapped in an object with key/value pairs. The key-string will act as value identifier, te

3条回答
  •  春和景丽
    2020-11-29 16:36

    Further to Stephen Weinberg's answer, I have since implemented a handy tool called iojson, which helps to populate data to an existing object easily as well as encoding the existing object to a JSON string. A iojson middleware is also provided to work with other middlewares. More examples can be found at https://github.com/junhsieh/iojson

    Example:

    func main() {
        jsonStr := `{"Status":true,"ErrArr":[],"ObjArr":[{"Name":"My luxury car","ItemArr":[{"Name":"Bag"},{"Name":"Pen"}]}],"ObjMap":{}}`
    
        car := NewCar()
    
        i := iojson.NewIOJSON()
    
        if err := i.Decode(strings.NewReader(jsonStr)); err != nil {
            fmt.Printf("err: %s\n", err.Error())
        }
    
        // populating data to a live car object.
        if v, err := i.GetObjFromArr(0, car); err != nil {
            fmt.Printf("err: %s\n", err.Error())
        } else {
            fmt.Printf("car (original): %s\n", car.GetName())
            fmt.Printf("car (returned): %s\n", v.(*Car).GetName())
    
            for k, item := range car.ItemArr {
                fmt.Printf("ItemArr[%d] of car (original): %s\n", k, item.GetName())
            }
    
            for k, item := range v.(*Car).ItemArr {
                fmt.Printf("ItemArr[%d] of car (returned): %s\n", k, item.GetName())
            }
        }
    }
    

    Sample output:

    car (original): My luxury car
    car (returned): My luxury car
    ItemArr[0] of car (original): Bag
    ItemArr[1] of car (original): Pen
    ItemArr[0] of car (returned): Bag
    ItemArr[1] of car (returned): Pen
    

提交回复
热议问题