dpvmjk0479 2016-12-02 14:08
浏览 27
已采纳

始终将JSON解组为特定类型(字符串)

I have some JSON that can have either a number or a string as the first element. I always want to be able to store this as a string value but instead I get a crash as it is reading it as quite rightly so a number type.

I tried to force the unmarshalling as a string but this was not successful.

string `json:",string"`

I am following this guide which seems to fit my data nicely.

How can I always get this element at [0] to always read and save as a string?

Code & Playground below...

https://play.golang.org/p/KP4_1xPJiZ

package main

import "fmt"
import "log"
import "encoding/json"

const inputWorking = `
["AAAAAA", {"testcode" : "Sss"}, 66666666]
`

const inputBroken = `
[111111, {"testcode" : "Sss"}, 66666666]
`

type RawMessage struct {
    AlwaysString        string `json:",string"`
    ClientData    ClientData
    ReceptionTime int
}

type ClientData struct {
    testcode string
}

func main() {

    var n RawMessage
    if err := json.Unmarshal([]byte(inputWorking), &n); err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%#v
", n)

    var o RawMessage
    if err := json.Unmarshal([]byte(inputBroken), &o); err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%#v
", o)
}

func (n *RawMessage) UnmarshalJSON(buf []byte) error {
    tmp := []interface{}{&n.AlwaysString, &n.ClientData, &n.ReceptionTime}
    wantLen := len(tmp)
    if err := json.Unmarshal(buf, &tmp); err != nil {
        return err
    }
    if g, e := len(tmp), wantLen; g != e {
        return fmt.Errorf("wrong number of fields in RawMessage: %d != %d", g, e)
    }
    return nil
}
  • 写回答

3条回答 默认 最新

  • douxin8610 2016-12-02 14:50
    关注

    You can create a universal receiver, i.e. of interface type, and then do a type assertion:

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type RawMessage struct {
        UnknownType interface{} `json:"unknown_type"`
    }
    
    const inputString = `{"unknown_type" : "a"}`
    
    const inputFloat = `{"unknown_type" : 123}` // Note: Unmarshals into a float64 by default!!!
    
    func main() {
    
        var n RawMessage
        if err := json.Unmarshal([]byte(inputFloat), &n); err != nil {
            println(err.Error())
        }
    
        switch v := n.UnknownType.(type) {
        case string:
            fmt.Printf("Received a string: %v", v)
        case float64:
            fmt.Printf("Received a number: %v", v)
        default:
            fmt.Printf("Unknown type: %v", v)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。