Parsing JSON in Golang without Redundant Unmarshaling
When dealing with JSON data containing different message types, unmarshaling directly into known struct types may not be feasible. Instead, a two-step process can be employed to resolve this issue.
Step 1: Unmarshal into a Generic Map
Unmarshal the JSON object into a generic map[string]interface{} to retrieve the top-level keys and values.
Step 2: Identify and Unmarshal Specific Keys
Iterate through the map and identify the key corresponding to the desired message type. For example:
switch k { case "ping": // ... case "ack": // ... }
For each identified key, unmarshal the corresponding value into a json.RawMessage instead of an interface{}:
var myAck json.RawMessage
Step 3: Unmarshal into Specific Struct
Finally, to convert the RawMessage into the desired struct, directly unmarshal it without the need for an intermediate marshal/unmarshal process:
err = json.Unmarshal(myAck, &myAck)
By partially unmarshaling into RawMessage and avoiding redundant unmarshaling, this approach simplifies the process and improves efficiency when parsing complex JSON data.
The above is the detailed content of How to Efficiently Parse JSON with Multiple Message Types in Go?. For more information, please follow other related articles on the PHP Chinese website!