2012-02-26 40 views
54

我需要一個JSON字符串,如浮點數解碼:如何解碼JSON的類型從字符串轉換爲Golang中的float64?

{"name":"Galaxy Nexus", "price":"3460.00"} 

我用下面的Golang代碼:

package main 

import (
    "encoding/json" 
    "fmt" 
) 

type Product struct { 
    Name string 
    Price float64 
} 

func main() { 
    s := `{"name":"Galaxy Nexus", "price":"3460.00"}` 
    var pro Product 
    err := json.Unmarshal([]byte(s), &pro) 
    if err == nil { 
     fmt.Printf("%+v\n", pro) 
    } else { 
     fmt.Println(err) 
     fmt.Printf("%+v\n", pro) 
    } 
} 

當我運行它,得到的結果是:

json: cannot unmarshal string into Go value of type float64 
{Name:Galaxy Nexus Price:0} 

我想知道如何解碼類型轉換的JSON字符串。

回答

112

答案是相當少的複雜。只需添加告訴JSON interpeter這是一個字符串編碼float64與,string(請注意,我只是改變了Price定義):

package main 

import (
    "encoding/json" 
    "fmt" 
) 

type Product struct { 
    Name string 
    Price float64 `json:",string"` 
} 

func main() { 
    s := `{"name":"Galaxy Nexus", "price":"3460.00"}` 
    var pro Product 
    err := json.Unmarshal([]byte(s), &pro) 
    if err == nil { 
     fmt.Printf("%+v\n", pro) 
    } else { 
     fmt.Println(err) 
     fmt.Printf("%+v\n", pro) 
    } 
} 
+0

謝謝!我認爲這是解決我的問題的最佳解決方案。你能告訴我關於「,字符串」用法的官方文件在哪裏? – yanunon 2012-03-06 02:35:05

+5

我在[link](http://weekly.golang.org/pkg/encoding/json/)上找到了它。 – yanunon 2012-03-06 02:47:29

+0

+1太棒了。我不知道這件事。 – Mostafa 2012-03-06 10:20:02

5

在引號中傳遞值使其看起來像字符串。將"price":"3460.00"更改爲"price":3460.00,一切正常。

如果您不能刪除引號,你必須自己,解析它使用strconv.ParseFloat

package main 

import (
    "encoding/json" 
    "fmt" 
    "strconv" 
) 

type Product struct { 
    Name  string 
    Price  string 
    PriceFloat float64 
} 

func main() { 
    s := `{"name":"Galaxy Nexus", "price":"3460.00"}` 
    var pro Product 
    err := json.Unmarshal([]byte(s), &pro) 
    if err == nil { 
     pro.PriceFloat, err = strconv.ParseFloat(pro.Price, 64) 
     if err != nil { fmt.Println(err) } 
     fmt.Printf("%+v\n", pro) 
    } else { 
     fmt.Println(err) 
     fmt.Printf("%+v\n", pro) 
    } 
} 
+0

有沒有辦法不改變'產品'結構和實現解碼函數或接口來解析字符串浮動? – yanunon 2012-02-26 13:26:05

+1

@yanunon是的,你可以爲'Unmarshal'使用'map [string] interface {}'類型的映射,並將其解析到你的結構中。 – Mostafa 2012-02-26 14:11:11

+0

@yanunon或者如果你想要**真正的**靈活性,你可以編寫自己的'Unmarshal',它使用'map [string] interface {}'調用默認的'Unmarshal',但使用'reflect'和'strconv'包來解析。 – Mostafa 2012-02-26 14:18:20

4

只是讓你知道你可以做到這一點沒有Unmarshal和使用json.decode。這裏是Go Playground

package main 

import (
    "encoding/json" 
    "fmt" 
    "strings" 
) 

type Product struct { 
    Name string `json:"name"` 
    Price float64 `json:"price,string"` 
} 

func main() { 
    s := `{"name":"Galaxy Nexus","price":"3460.00"}` 
    var pro Product 
    err := json.NewDecoder(strings.NewReader(s)).Decode(&pro) 
    if err != nil { 
     fmt.Println(err) 
     return 
    } 
    fmt.Println(pro) 
} 
相關問題