Home  >  Article  >  Backend Development  >  How to Unmarshall Arbitrary JSON Data in Sections Based on a Code?

How to Unmarshall Arbitrary JSON Data in Sections Based on a Code?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-31 21:27:02998browse

How to Unmarshall Arbitrary JSON Data in Sections Based on a Code?

Unmarshalling Arbitrary Data in JSON

In certain scenarios, it may be necessary to unmarshall JSON data in parts or sections. For instance, the upper half of the data might indicate the action to perform on the lower half, such as unmarshalling into a specific struct based on the "code" in the upper half.

Consider the following sample structures:

<code class="go">type Range struct {
    Start int
    End   int
}

type User struct {
    ID    int
    Pass  int
}</code>

As an example, the JSON data could resemble the following:

<code class="json">// Message with "Code" 4, signifying a Range structure
{
    "Code": 4,
    "Payload": {
        "Start": 1,
        "End": 10
    }
}

// Message with "Code" 3, signifying a User structure
{
    "Code": 3,
    "Payload": {
        "ID": 1,
        "Pass": 1234
    }
}</code>

To achieve this unmarshalling, we can delay parsing the bottom half of the JSON data until we have determined the code in the top half. Consider the following approach:

<code class="go">import (
    "encoding/json"
    "fmt"
)

type Message struct {
    Code    int
    Payload json.RawMessage // Delay parsing until we know the code
}

func MyUnmarshall(m []byte) {
    var message Message
    var payload interface{}
    json.Unmarshal(m, &message) // Delay parsing until we know the color space
    switch message.Code {
    case 3:
        payload = new(User)
    case 4:
        payload = new(Range)
    }
    json.Unmarshal(message.Payload, payload) // Error checks omitted for readability
    fmt.Printf("\n%v%+v", message.Code, payload) // Perform actions on the data
}

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>

By using this approach, you can effectively unmarshall arbitrary JSON data in sections, depending on the specified code.

The above is the detailed content of How to Unmarshall Arbitrary JSON Data in Sections 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