dongyan9838 2014-08-07 13:41
浏览 81
已采纳

如何将一个字符串编码的浮点数解组为一个浮点数数组?

I'm trying to unmarshal some json data I get from a web service. I have simplified the problem which is shown in the code below. My question is can I make version (c) in the code work..

I know it works for single number values as shown for "timestamp" by adding the option ",string" to the json annotation. But I can't figure out how or if this works for arrays of string encoded numbers too. (See "conversions" in the example json listed in the code)

package main

import (
    "encoding/json"
    "fmt"    
)

//version (a)
type JsonData1 struct {
    TimeStamp   uint64          `json:"timestamp,string"`
    Conversions [][2]string     `json:"conversions"`
}

//version (b)
type JsonData2 struct {
    TimeStamp   uint64              `json:"timestamp,string"`
    Conversions [][2]json.Number    `json:"conversions"` 
}

//version (c)
type JsonData3 struct {
    TimeStamp   uint64          `json:"timestamp,string"`
    Conversions [][2]float32    `json:"conversions"` 
}

const incomingJson string = `{"timestamp": "1407178369", "conversions": [["1.021", "2.124"], ["2.432", "3.923"], ["3.234", "5.001"]]}`

func main() {
    var data1 JsonData1
    if err1 := json.Unmarshal([]byte(incomingJson), &data1); err1 != nil {
        fmt.Println("Error unmarshaling with struct JsonData1")
        fmt.Println("--> ", err1.Error())
    } else {
        fmt.Println("Success unmarshaling with struct JsonData1")
        fmt.Println("--> ", data1)
    }

    var data2 JsonData2
    if err2 := json.Unmarshal([]byte(incomingJson), &data2); err2 != nil {
        fmt.Println("Error unmarshaling with struct JsonData2")
        fmt.Println("--> ", err2.Error())
    } else {
        fmt.Println("Success unmarshaling with struct JsonData2")
        fmt.Println("--> ", data2)
    }    

    var data3 JsonData3
    if err3 := json.Unmarshal([]byte(incomingJson), &data3); err3 != nil {
        fmt.Println("Error unmarshaling with struct JsonData3")
        fmt.Println("--> ", err3.Error())
    } else {
        fmt.Println("Success unmarshaling with struct JsonData3")
        fmt.Println("--> ", data3)
    }  
}

If i compile and run the code I get this output:

Success unmarshaling with struct JsonData1
-->  {1407178369 [[1.021 2.124] [2.432 3.923] [3.234 5.001]]}
Success unmarshaling with struct JsonData2
-->  {1407178369 [[1.021 2.124] [2.432 3.923] [3.234 5.001]]}
Error unmarshaling with struct JsonData3
-->  json: cannot unmarshal string into Go value of type float32

You can run the code here: http://play.golang.org/p/4TC0IgCI8H

Is there a way to achieve unmarshaling into struct version (c)? Thanks for your help!

  • 写回答

3条回答 默认 最新

  • dongyan5239 2014-08-07 14:09
    关注

    The easiest way I know to do this is to define a new type and then define UnmarshalJSON for it:

    type Conversions [][2]float64
    
    func (c *Conversions) UnmarshalJSON(b []byte) error {
        tmp := [][2]json.Number{}
        if err := json.Unmarshal(b, &tmp); err != nil {
            return err
        }
    
        *c = make(Conversions, len(tmp))
        for i, a := range tmp {
            var (
                pair [2]float64
                err  error
            )
            pair[0], err = a[0].Float64()
            if err != nil {
                return err
            }
            pair[1], err = a[1].Float64()
            if err != nil {
                return err
            }
            (*c)[i] = pair
        }
        return nil
    }
    

    Playground, see version (d). This is not the most perfect way to do that and the algorithm can be improved to use less resources, but you get the idea.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)