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

时间:2017-05-28 05:29:26

标签: json list go

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

输出:

  

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”:{},“phone”:{},“uid”:“306”}   好的golang-test / com / http / test 0.482s

手机应该是列表值,但没有。帮助我。

1 个答案:

答案 0 :(得分:1)

由于List类型没有导出字段且类型未实现Marshaler接口,因此列表值始终编组为文本{}

一个简单的解决方法是使用切片而不是列表:

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

playground example