Home  >  Article  >  Backend Development  >  How to Unmarshal Arbitrary JSON Data with Varying Structures Based on a \"Code\"?

How to Unmarshal Arbitrary JSON Data with Varying Structures Based on a \"Code\"?

Linda Hamilton
Linda HamiltonOriginal
2024-10-30 10:21:03531browse

How to Unmarshal Arbitrary JSON Data with Varying Structures Based on a

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:

  1. Define a Message struct with an int Code field and a json.RawMessage Payload field. This field will temporarily store the unparsed bottom half.
  2. Create functions to parse and unmarshall the different struct types based on the Code.
  3. Unmarshal the Message struct from the JSON data. This will parse the top half of the data and delay parsing the bottom half.
  4. Based on the Code, create an instance of the appropriate struct type and unmarshall the Payload into it.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn