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

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

針對相同對象值的不同 API 響應

針對相同對象值的不同 API 響應

Go
心有法竹 2022-10-04 19:04:19
下面是代碼示例:func GetValue(c echo.Context) error {    //other implementation details        value, err := service.GetValue()    if err != nil {        return c.JSON(http.StatusBadRequest, errorresponse.Error(4003, err))    }    //if I set same value here, it works as expected    //value.Value = []int8{48, 48, 48, 54, 54, 49, 56, 54, 32, 32, 32, 32, 32, 32, 32}    return c.JSON(http.StatusOK, value)} //this is type service.GetValue() returnstype ValueGetResponse struct {    Value     interface{}    ValueType string}如果我使用來自方法的值,API 會給我一個類似于波紋管的響應。它把它轉換成某種我不知道的字符串。當我檢查屬性時,說,它是一個as類型。此外,VSCode 調試器也會批準它。service.GetValue()value.Valuereflect.TypeOf(value.Value)[]int8請求中使用的對象:回應:{    "Value": "MDAwNjYxODYgICAgICAg",    "ValueType": "[]uint8"}如果我手動設置期望值,它按預期工作,我不明白為什么第一個不是。value.Value = []int8{48, 48, 48, 54, 54, 49, 56, 54, 32, 32, 32, 32, 32, 32, 32}請求中使用的對象:回應:{    "Value": [        48,        48,        48,        54,        54,        49,        56,        54,        32,        32,        32,        32,        32,        32,        32,        32    ],    "ValueType": "[]uint8"}
查看完整描述

1 回答

?
回首憶惘然

TA貢獻1847條經驗 獲得超11個贊

在Golang中是別名,當您使用它時,它返回與您的數據類型相同的類型。因此,當您收到此類數據時,它會轉換為字符串。byteuint8json.Marshal[]byte


您需要將 uint8 強制轉換為其他 int 類型或實現Marshaler interface



bytes, err := service.GetValue()

value := make([]int8, 0)

for _, v := range bytes {

    value = append(value, int8(v))

}

元帥


type CustomType []uint8


func (u CustomType) MarshalJSON() ([]byte, error) {

    var result string

    if u == nil {

        result = "null"

    } else {

        result = strings.Join(strings.Fields(fmt.Sprintf("%d", u)), ",")

    }

    return []byte(result), nil

}


func GetValue(c echo.Context) error {

    var value CustomType

    bytes, err := service.GetValue()

    value = bytes


    return c.JSON(http.StatusOK, value)

}


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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