亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將包含數組的 JSON 對象轉換為單個 Struct 實例

如何將包含數組的 JSON 對象轉換為單個 Struct 實例

Go
慕雪6442864 2023-07-10 14:36:49
我意識到有很多類似的問題,但我仍然無法找到我的問題的答案。我的 JSON 文件的相關部分如下所示:{     ...,    "roi": {        "roi": [            {                "id": "original",                "x": 600,                "y": 410,                "width": 540.0,                "height": 240.0            }        ]    },    ...}這是我定義結構的方式:type RoI struct {    Id     string  `json:"string"`                            // Default Value: "original"    Width  float64 `json:"width" validate:"gte=0,lte=10000"`  // RoI width (from 0 - 10000) - how much we move to the right from (X,Y) point    Height float64 `json:"height" validate:"gte=0,lte=10000"` // RoI height (from 0 - 10000) - how much we move down from the (X,Y) point    X      float64 `json:"x" validate:"gte=0,lte=10000"`      // X coordinate which together with Y coordinate forms a top left corner of the RoI (from 0 - 10000)    Y      float64 `json:"y" validate:"gte=0,lte=10000"`      // Y coordinate which together with X coordinate forms a top left corner of the RoI (from 0 - 10000)}我假設我總是會在"roi"數組中獲得 1 個元素。請注意,我需要保留此結構用于許多不同的目的。我想將roi數組內的 1 個元素解析為RoI結構體。這是我到目前為止所嘗試過的:var detectionResMap = make(map[string]interface{})err = json.Unmarshal(fileByteArr, &detectionResMap)if err != nil {    glog.Errorf("Error occurred while trying to Unmarshal JSON data into detectionResMap. Error message - %v", err)    return err}當我使用以下方式打印時detectionResMap["roi"]:glog.Infof("[INFO]: %v", reflect.TypeOf(detectionResMap["roi"]))glog.Infof("[INFO]: %v", detectionResMap["roi"])我得到以下輸出:I0801 19:56:45.392362  125787 v2.go:87] [INFO]: map[string]interface {}I0801 19:56:45.392484  125787 v2.go:88] [INFO]: map[roi:[map[height:240 id:original width:540 x:600 y:410]]]我得到以下信息: { 0 0 0 0}如果我嘗試將其更改為[]RoI:json: cannot unmarshal object into Go value of type []config.RoI任何幫助將不勝感激
查看完整描述

1 回答

?
大話西游666

TA貢獻1817條經驗 獲得超14個贊

您的嘗試不起作用,因為roiByteArr, {"roi": [{ ... }]}this 不匹配config.RoI也不匹配[]config.RoI。


您可以聲明一個與 json 匹配的類型:


type roiobj struct {

    RoI struct {

        RoI []RoI `json:"roi"`

    } `json:"roi"`

}


var obj roiobj

if err := json.Unmarshal(fileByteArr, &obj); err != nil {

    panic(err)

}

roi := obj.RoI.RoI[0]

操場

或者正確檢索與您的結構相匹配的對象:


// in your real code do not omit safe type assertion like i'm doing here.

obj := detectionResMap["roi"].(map[string]interface{})["roi"].([]interface{})[0]

roiByteArr, err := json.Marshal(obj)

if err != nil {

    return err

}


roi := config.RoI{}

if err := json.Unmarshal(roiByteArr, &roi); err != nil {

    return err

}

操場

或者實現自定義解組器:


func (r *RoI) UnmarshalJSON(b []byte) error {

    type roi RoI

    var obj struct {

        RoI []roi

    }

    if err := json.Unmarshal(b, &obj); err != nil {

        return err

    }

    *r = RoI(obj.RoI[0])

    return nil

}


var fileobj struct {

    // ...

    RoI RoI `json:"roi"`

    // ...

}

if err := json.Unmarshal(fileByteArr, &fileobj); err != nil {

    panic(err)

}

roi := fileobj.RoI

操場


查看完整回答
反對 回復 2023-07-10
  • 1 回答
  • 0 關注
  • 123 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號