dpzff20644 2017-05-28 05:29
浏览 548

为什么我将map转换为json,map包含列表值,转换为json后什么都没有

func Test_JsonTtransfer(t *testing.T) {

    uid := "306"
    phoneList := list.New()
    phoneList.PushBack("18513622928")
    fmt.Println("phoneList=======", phoneList.Len())


    jsonPhoneList, err := json.Marshal(phoneList)
    if err != nil {
        fmt.Println("error:", err)
    }
    fmt.Println("jsonPhoneList=======", string(jsonPhoneList))

    idCardList := list.New()
    idCardList.PushBack("230405197608040640")

    request := make(map[string]interface{})
    request["uid"] = uid

    request["phones"] = phoneList

    request["id_cards"] = idCardList

    json, err := json.Marshal(request)
    if err != nil {
        fmt.Println("error:", err)
    }

    fmt.Println("json=======", json)
    fmt.Println("json=======", string(json))
}

Output:

D:/Sys/server/Go\bin\go.exe test -v golang-test/com/http/test -run ^Test_JsonTtransfer$ phoneList======= 1 jsonPhoneList======= {} json======= [123 34 105 100 95 99 97 114 100 115 34 58 123 125 44 34 112 104 111 110 101 115 34 58 123 125 44 34 117 105 100 34 58 34 51 48 54 34 125] json======= {"id_cards":{},"phones":{},"uid":"306"} ok golang-test/com/http/test 0.482s

Phones should be list values, but nothing. Help me.

  • 写回答

1条回答 默认 最新

  • douyan2002 2017-05-28 06:01
    关注

    Because the List type has no exported fields and the type does not implement the Marshalerinterface, List values always marshal to the text {}.

    A simple fix is to use a slice instead of a list:

    var phoneList []string
    phoneList = append(phoneList, "18513622928")
    fmt.Println("phoneList=======", len(phoneList)
    

    playground example

    评论

报告相同问题?

悬赏问题

  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上