Lee Armstrong
Lee Armstrong

Reputation: 11450

Unmarshalling JSON to certain type (string) always

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", 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
}

Upvotes: 3

Views: 1451

Answers (3)

byrnedo
byrnedo

Reputation: 1465

I had the same problem and so far the best I found was to make a type from string with a custom 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)
}

Try it yourself at https://goplay.space/#i0OVs9tnule

Upvotes: 3

oharlem
oharlem

Reputation: 1010

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)
    }
}

Upvotes: 3

Brij
Brij

Reputation: 269

Try this if it resolve this issue, make a generic interface as user input is not defined

interface{} `json:",string"`

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        interface{} `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)
    }

Upvotes: -1

Related Questions