我有一些JSON可以有一个数字或一个字符串作为第一个元素。我总是希望能够将其存储为字符串值,但我得到了一个崩溃,因为它正确地读取它是一个数字类型。
我试图将解组强制为字符串,但这并不成功。
string `json:",string"`
我正在关注此guide,这似乎很适合我的数据。
如何始终在[0]处获取此元素以始终读取并保存为字符串?
代码&下面的游乐场......
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", n)
var o RawMessage
if err := json.Unmarshal([]byte(inputBroken), &o); err != nil {
log.Fatal(err)
}
fmt.Printf("%#v\n", 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
}
答案 0 :(得分:2)
您可以创建通用接收器,即接口类型,然后执行类型断言:
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)
}
}
答案 1 :(得分:1)
我遇到了同样的问题,到目前为止,我发现最好的是使用自定义unmarshaller从字符串创建一个类型:
package main
import (
"encoding/json"
"fmt"
"strconv"
)
// Stringish exists because api send back integers unquoted even if underlying type is string
type StringIsh string
func (f *StringIsh) UnmarshalJSON(data []byte) error {
var receiver string
if len(data) == 0 {
return nil
}
if data[0] != '"' {
quoted := strconv.Quote(string(data))
data = []byte(quoted)
}
if err := json.Unmarshal(data, &receiver); err != nil {
return err
}
*f = StringIsh(receiver)
return nil
}
type Test struct {
Foo StringIsh
}
func main() {
dest := &Test{}
_ = json.Unmarshal([]byte(`{"foo": "bar"}`), &dest)
fmt.Println(dest)
dest = &Test{}
_ = json.Unmarshal([]byte(`{"foo": 123}`), &dest)
fmt.Println(dest)
}
处自行尝试
答案 2 :(得分:-1)
如果解决此问题,请尝试此操作,在未定义用户输入的情况下创建通用接口
rake assets:precompile production --trace
** Invoke assets:precompile (first_time)
** Invoke assets:environment (first_time)
** Execute assets:environment
** Invoke environment (first_time)
** Execute environment
** Execute assets:precompile
rake aborted!
Don't know how to build task 'production' (see --tasks)
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-11.3.0/lib/rake/task_manager.rb:71:in `[]'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-11.3.0/lib/rake/application.rb:151:in `invoke_task'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-11.3.0/lib/rake/application.rb:108:in `block (2 levels) in top_level'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-11.3.0/lib/rake/application.rb:108:in `each'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-11.3.0/lib/rake/application.rb:108:in `block in top_level'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-11.3.0/lib/rake/application.rb:117:in `run_with_threads'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-11.3.0/lib/rake/application.rb:102:in `top_level'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-11.3.0/lib/rake/application.rb:80:in `block in run'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-11.3.0/lib/rake/application.rb:178:in `standard_exception_handling'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-11.3.0/lib/rake/application.rb:77:in `run'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-11.3.0/exe/rake:27:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.3.1/bin/rake:23:in `load'
/usr/local/rvm/gems/ruby-2.3.1/bin/rake:23:in `<main>'
package main
interface{} `json:",string"`