I have a struct as
type Result struct {
Foo *string
}
I would like to get a json object like
{"Foo": null}
How do I achieve this ?
I have tried a few things: approach 1:
var res1 *Result
json.Unmarshal(nil, &res1)
approach2
var res1 Result
res1.Foo = nil
I get a res1 struct with Foo as nil
Thanks for help!
Edit: var res1 *Result -> var res1 Result
CodePudding user response:
Basic types in Go are not nillable. string
is a basic type.
In order for Foo
to be nillable, one solution is to make it a string pointer. That would look like this:
type Result struct {
Foo *string
}
If you don't like nil
, you can also add a boolean field explaining if Foo
is present or not:
type Result struct {
Foo string
IsPresent bool // true if Foo is present. false otherwise.
}
But you would need to write a custom JSON deserializer for this. So just making Foo
a pointer is what I would do.
Edit after question was changed to mention OP already is using *string
:
To go from the JSON string { "Foo" : null }
to the Result
Go struct listed above in my answer, the json
package Unmarshal
function can be used:
var r Result
err := json.Unmarshal([]byte(`{ "Foo" : null }`), &r)
if err != nil { /* ... */ }
// now f contains the desired data
To convert from the Result
struct to the above JSON string, the json
library Marshal
function can be used:
var r Result // Foo will be zero'd to nil
jsonStr, err := json.Marshal(&r)
if err != nil { /* ... */ }
// now jsonStr contains `{ "Foo" : null }`
Here are the above two code blocks running in Go Playground.