猿问

针对相同对象值的不同 API 响应

下面是代码示例:


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() returns

type 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}

请求中使用的对象:

http://img4.mukewang.com/633c14020001e88405510325.jpg

回应:


{

    "Value": [

        48,

        48,

        48,

        54,

        54,

        49,

        56,

        54,

        32,

        32,

        32,

        32,

        32,

        32,

        32,

        32

    ],

    "ValueType": "[]uint8"

}


心有法竹
浏览 113回答 1
1回答

回首忆惘然

在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 []uint8func (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)}
随时随地看视频慕课网APP

相关分类

Go
我要回答