自定义解组 golang - 对象或 int

问题描述 投票:0回答:1

我正在尝试解组 API 的响应,其中

status
可以是对象或整数:

    "status": {
        "title": "Bad Request",
        "statusCode": 400,
        "detail": "Your request contained technical errors as listed below."
    },
    "items": [
        {
            "propertyPath": "shipments[0].services.visualCheckOfAge",
            "message": "Parameter visualCheckOfAge only allows the values A16 or A18."
        }
    ]
}

    "status": 401,
    "title": "Unauthorized",
    "detail": "Unauthorized for given resource."
}

我试过像这样自定义解组但它失败了:

type ShipmentOrderResponse struct {
    Status Status  `json:"status"`
    Title  string  `json:"title,omitempty"`
    Detail string  `json:"detail,omitempty"`
    Items  *[]Item `json:"items,omitempty"`
}

type Status struct {
    Title string `json:"title,omitempty"`
    Code  int    `json:"statusCode,omitempty"`
    // Instance A URI reference that identifies the specific occurrence of the problem.
    Instance string `json:"instance,omitempty"`
    // Detail Defines details about the status of the response.
    Detail string `json:"detail,omitempty"`
}
func (s *Status) UnmarshalJSON(d []byte) error {
    for _, b := range d {
        switch b {
        // These are the only valid whitespace in a JSON object.
        case ' ', '\n', '\r', '\t':
        case '{':
            var obj Status
            if err := json.Unmarshal(d, &obj); err != nil {
                return err
            }
            *s = obj
            return nil
        default:
            var code int
            err := json.Unmarshal(d, &code)
            if err != nil {
                return err
            }
            s.Code = code
            return nil
        }
    }
    return errors.New("status must be object or int")
}

任何提示,我将不胜感激,如何解决这个问题。

谢谢。

go unmarshalling
1个回答
0
投票

用这个方法。

func (s *Status) UnmarshalJSON(d []byte) error {
    // Is it an object? 
    if d[0] == '{' {
        // Define a type to break recursion. Type X has the same
        // fields as Status, but no methods. In particular, type
        // X does not have a UnmarshalJSON method.
        type X Status
        return json.Unmarshal(d, (*X)(s))
    }
    // Assume an integer.
    return json.Unmarshal(d, &s.Code)
}

https://go.dev/play/p/3BoYg09qr7B

不需要跳过问题中空格的循环,因为 UnmarshalJSON 的数据参数不包括 值前的空格。

© www.soinside.com 2019 - 2024. All rights reserved.