为了账号安全,请及时绑定邮箱和手机立即绑定

针对相同对象值的不同 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 关注
  • 112 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号