Skip to content

Commit 8ba1a30

Browse files
Go fix
1 parent c09fe6f commit 8ba1a30

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

go/rpc/result_union.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package rpc
2+
3+
import "encoding/json"
4+
5+
// MarshalJSON serializes ResultUnion as the appropriate JSON variant:
6+
// a plain string when String is set, or the ResultResult object otherwise.
7+
// The generated struct has no custom marshaler, so without this the Go
8+
// struct fields would serialize as {"ResultResult":...,"String":...}
9+
// instead of the union the server expects.
10+
func (r ResultUnion) MarshalJSON() ([]byte, error) {
11+
if r.String != nil {
12+
return json.Marshal(*r.String)
13+
}
14+
if r.ResultResult != nil {
15+
return json.Marshal(*r.ResultResult)
16+
}
17+
return []byte("null"), nil
18+
}
19+
20+
// UnmarshalJSON deserializes a JSON value into the appropriate ResultUnion variant.
21+
func (r *ResultUnion) UnmarshalJSON(data []byte) error {
22+
// Try string first
23+
var s string
24+
if err := json.Unmarshal(data, &s); err == nil {
25+
r.String = &s
26+
return nil
27+
}
28+
// Try ResultResult object
29+
var rr ResultResult
30+
if err := json.Unmarshal(data, &rr); err == nil {
31+
r.ResultResult = &rr
32+
return nil
33+
}
34+
return nil
35+
}

0 commit comments

Comments
 (0)