Home > Article > Backend Development > How to Unmarshall JSON Data Dynamically Based on a Code Value?
Arbitrary Data Unmarshalling
In many scenarios, it's necessary to unmarshall JSON data in a flexible manner, allowing the unmarshalling process to adapt to different data structures based on a predetermined code value. This enables dynamic interpretation of data received from various sources.
For example, consider a JSON message that contains a "code" field, which specifies the type of data contained in the "payload" field. The "payload" field could represent a different data structure depending on the "code" value.
To achieve this, we can use the following technique:
<code class="go">package main import ( "encoding/json" "fmt" ) type Message struct { Code int Payload json.RawMessage // delay parsing until we know the code } // Define the possible data structures that can be unmarshalled from the "payload" field type Range struct { Start int End int } type User struct { ID int Pass int } // Custom unmarshalling function func MyUnmarshall(m []byte) { var message Message var payload interface{} json.Unmarshal(m, &message) // delay parsing until we know the color space // Determine the data structure based on the "code" field switch message.Code { case 3: payload = new(User) case 4: payload = new(Range) } // Unmarshall the "payload" field into the appropriate data structure json.Unmarshal(message.Payload, payload) //err check ommited for readability // Do something with the unmarshalled data 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>
In this example, the MyUnmarshall function receives a JSON message, stores the "code" and "payload" fields in a Message struct, and then dynamically creates a data structure instance based on the "code" value. It subsequently unmarshals the "payload" field into the appropriate structure and performs desired actions on the unmarshalled data.
The above is the detailed content of How to Unmarshall JSON Data Dynamically Based on a Code Value?. For more information, please follow other related articles on the PHP Chinese website!