Well, if I were you, I would rather write some function convert map[int]string to map[string]string and then use the existing json pkg.
You could, but then you'd no longer be encoding to JSON:
JSON only supports string keys in objects. JavaScript's object literal
syntax, OTOH, supports a far wider range of key types, and syntaxes for
that (e.g. unquoted strings, single-quotes, etc.).
--
Arlen Cuss
Software Engineer
Phone: +61 3 9877 9921
Email: ar...@noblesamurai.com
Noble Samurai Pty Ltd
Level 1, 234 Whitehorse Rd
Nunawading, Victoria, 3131, Australia
Yes. The simplest example is json.RawMessage:
// RawMessage is a raw encoded JSON object.
// It implements Marshaler and Unmarshaler and can
// be used to delay JSON decoding or precompute a JSON encoding.
type RawMessage []byte
// MarshalJSON returns *m as the JSON encoding of m.
func (m *RawMessage) MarshalJSON() ([]byte, os.Error) {
return *m, nil
}
// UnmarshalJSON sets *m to a copy of data.
func (m *RawMessage) UnmarshalJSON(data []byte) os.Error {
if m == nil {
return os.NewError("json.RawMessage: UnmarshalJSON on nil pointer")
}
*m = append((*m)[0:0], data...)
return nil
}
but you can use any type of your own as long as you
implement the MarshalJSON and UnmarshalJSON methods.
Russ
Russ
On 14 June 2011 13:32, Michael Lore <mi...@skyegg.com> wrote:
> That makes sense in a call to json.Unmarshal(), but not when I implement
> UnmarshalJSON() on my object which already has space allocated. In the
> example below, the json library is dictating the design of my structures. I
> am not sure why it can't just run on a pointer to the structure member I
> declared, if it's not already a pointer.
Because even if it did call NotAPointer.UnmarshalJSON() it's not
really going to unmarshal anything, because the method will be passed
a _copy_ of NotAPointer which will no longer exist once the call
returns. Consider
type Foo struct {
X int
}
func (f Foo) Add(y int) {
f.X += y
}
func main() {
f := Foo{3}
f.Add(4)
println(f.X)
}
This code will print 3, not 7. Because in Foo.Add f is a copy of the
receiver. Likewise if Foo.Add was called Foo.UnmarshalJSON
Because NotAPointer is a copy of whatever you passed in and
however hard you write to the copy it can't affect the original. So
it doesn't do that.
Chris
--
Chris "allusive" Dollin
Because even if it did call NotAPointer.UnmarshalJSON() it's not
i think that the reason that it does not is that reflect.AddressOf
was not available until recently, so the JSON package was
unable to create a pointer from a value, even when the value
was addressable.