douyuefu1372 2013-01-06 00:10
浏览 784
已采纳

如何在Go中将字节/ uint8数组封送为json数组?

I've got a struct with a []uint8 member and I'm writing it with json.Marshal. Trouble is, it's interpreting the uint8s as chars and it outputs a string rather than an array of numbers.

I can get this to work if it's a []int, but I don't want to have to allocate and copy over the items if I can avoid it. Can I?

  • 写回答

1条回答 默认 最新

  • douxuanling6523 2013-01-06 01:35
    关注

    According to the docs, a []byte will be encoded as a Base64 string.

    "Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON object."

    So I think that you may need to make your struct implement the Marshaler interface by implementing your own MarshalJSON method that makes a more desirable JSON array encoding out of your []uint8.

    Take this example:

    import "fmt"
    import "encoding/json"
    import "strings"
    
    type Test struct {
        Name  string
        Array []uint8
    }
    
    func (t *Test) MarshalJSON() ([]byte, error) {
        var array string
        if t.Array == nil {
            array = "null"
        } else {
            array = strings.Join(strings.Fields(fmt.Sprintf("%d", t.Array)), ",")
        }
        jsonResult := fmt.Sprintf(`{"Name":%q,"Array":%s}`, t.Name, array)
        return []byte(jsonResult), nil
    }
    
    func main() {
        t := &Test{"Go", []uint8{'h', 'e', 'l', 'l', 'o'}}
    
        m, err := json.Marshal(t)
        if err != nil {
            fmt.Println(err)
        }
        fmt.Printf("%s", m) // {"Name":"Go","Array":[104,101,108,108,111]}
    }
    

    http://play.golang.org/p/Tip59Z9gqs


    Or maybe a better idea would be to make a new type that has []uint8 as its underlying type, make that type a Marshaler, and use that type in your struct.

    import "fmt"
    import "encoding/json"
    import "strings"
    
    type JSONableSlice []uint8
    
    func (u JSONableSlice) 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
    }
    
    type Test struct {
        Name  string
        Array JSONableSlice
    }
    
    func main() {
        t := &Test{"Go", []uint8{'h', 'e', 'l', 'l', 'o'}}
    
        m, err := json.Marshal(t)
        if err != nil {
            fmt.Println(err)
        }
        fmt.Printf("%s", m) // {"Name":"Go","Array":[104,101,108,108,111]}
    }
    

    http://play.golang.org/p/6aURXw8P5d

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误