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

Mary-Kate Olsen
Release: 2024-10-31 21:27:02
Original
1012 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!