在Go中,我有一些来自第三方API的JSON,然后我正在尝试解析它:
b := []byte(`{"age":21,"married":true}`)
var response_hash map[string]string
_ = json.Unmarshal(b, &response_hash)但它失败了(response_hash变为空),并且Unmarshal只能处理带引号的JSON:
b := []byte(`{"age":"21","married":"true"}`)
var response_hash map[string]string
_ = json.Unmarshal(b, &response_hash)有没有办法从第三方API读取JSON的第一个版本?
发布于 2012-12-19 01:35:34
Go是一种强类型语言。您需要指定JSON编码器期望的类型。您正在创建字符串值的映射,但是您的两个json值是一个整数和一个布尔值。
下面是一个使用结构的工作示例。
http://play.golang.org/p/oI1JD1UUhu
package main
import (
"fmt"
"encoding/json"
)
type user struct {
Age int
Married bool
}
func main() {
src_json := []byte(`{"age":21,"married":true}`)
u := user{}
err := json.Unmarshal(src_json, &u)
if err != nil {
panic(err)
}
fmt.Printf("Age: %d\n", u.Age)
fmt.Printf("Married: %v\n", u.Married)
}如果你想以一种更动态的方式来实现,你可以使用一个interface{}值的映射。当您使用这些值时,您只需执行类型断言。
http://play.golang.org/p/zmT3sPimZC
package main
import (
"fmt"
"encoding/json"
)
func main() {
src_json := []byte(`{"age":21,"married":true}`)
// Map of interfaces can receive any value types
u := map[string]interface{}{}
err := json.Unmarshal(src_json, &u)
if err != nil {
panic(err)
}
// Type assert values
// Unmarshal stores "age" as a float even though it's an int.
fmt.Printf("Age: %1.0f\n", u["age"].(float64))
fmt.Printf("Married: %v\n", u["married"].(bool))
}https://stackoverflow.com/questions/13938352
复制相似问题