I need to marshal/unmarshal json to struct in golang. Assume the struct is
type A struct {
Id string `json:"id"`
Version string `json:"version"`
Actors []actor `json:"actors`
Payload struct {
Name string `json:"name"`
Number string `json:"number"`
}
}
type payload struct {
Name string `json:"name"`
Number string `json:"number"`
}
type actor struct {
Id string `json:"id"`
Type string `json:"type"`
Role string `json:"role"`
}
The actors or payload maybe empty. The json maybe
{
"id": "78a07cea-be2b-499c-b82b-e4f510260484",
"version": "1.0.0",
"actors": [
{
"id": "1234567",
"type": "XXX",
"role": "111"
},
{
"id": "7654321",
"type": "YYY",
"role": "222"
}
],
"payload": ""
}
or
{
"id": "78a07cea-be2b-499c-b82b-e4f510260484",
"version": "1.0.0",
"actors": [],
"payload": {
"name": "XXXX",
"number": "1234567"
}
}
If i follow the struct A design and try to marshal json with payload empty, i have to init as below
a := A{
Id: "78a07cea-be2b-499c-b82b-e4f510260484",
Version: "1.0.0",
Actors: []actor{
actor{
Id: "1234567",
Type: "XXX",
Role: "111",
},
actor{
Id: "7654321",
Type: "YYY",
Role: "222",
},
},
Payload: payload{},
}
Which will result in below json with one empty payload struct
{
"id": "78a07cea-be2b-499c-b82b-e4f510260484",
"version": "1.0.0",
"actors": [
{
"id": "1234567",
"type": "XXX",
"role": "111"
},
{
"id": "7654321",
"type": "YYY",
"role": "222"
}
],
"payload": {
"name":"",
"number":""
}
}
Is there any way i can generate
"payload": ""
instead of blank payload struct? Or is there any other struct design for this kind of json format? BTW i cannot pass nil to Payload struct.