Home > Article > Backend Development > How to Unmarshal Arbitrary JSON Data with Varying Structures Based on a \"Code\"?
Unmarshalling Arbitrary JSON Data
Question:
Can JSON data be marshalled in a way that allows it to be unmarshalled in parts or sections? In this scenario, the top half of the data defines a "code" that indicates the type of data in the bottom half, which may vary between structs. How can this be achieved in Go?
Answer:
To unmarshall arbitrary JSON data where the bottom half can vary between structs, you can delay parsing the bottom half until the "code" from the top half is known.
Implementation:
Example Code:
<code class="go">package main import ( "encoding/json" "fmt" ) type Message struct { Code int Payload json.RawMessage } type Range struct { Start int End int } type User struct { ID int Pass int } func MyUnmarshall(m []byte) { var message Message var payload interface{} json.Unmarshal(m, &message) switch message.Code { case 3: payload = new(User) case 4: payload = new(Range) } json.Unmarshal(message.Payload, payload) fmt.Printf("\n%v%+v", message.Code, payload) } func main() { json := []byte(`{"Code": 4, "Payload": {"Start": 1, "End": 10}}`) MyUnmarshall(json) json = []byte(`{"Code": 3, "Payload": {"ID": 1, "Pass": 1234}}`) MyUnmarshall(json) }</code>
The above is the detailed content of How to Unmarshal Arbitrary JSON Data with Varying Structures Based on a \"Code\"?. For more information, please follow other related articles on the PHP Chinese website!