How to Unmarshal Non-Homogenous JSON Data with a \'Code\' Field?

Mary-Kate Olsen
Release: 2024-11-03 06:49:02
Original
402 people have browsed it

How to Unmarshal Non-Homogenous JSON Data with a

Unmarshalling Non-Homogenous JSON Data

This inquiry centers around unmarshalling JSON data efficiently by leveraging a mechanism that allows for selective unmarshalling of specific sections or segments. The objective is to handle JSON structures where the first part serves as a "code" that determines the type of data contained in the latter part.

Imagine a scenario where you have multiple data structures:

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

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

And your JSON message has a "code" field that signals what data is in the "payload" field:

<code class="json">{
    "Code": 4,
    "Payload": {
        "Start": 1,
        "End": 10
    }
}
{
    "Code": 3,
    "Payload": {
        "ID": 1,
        "Pass": 1234
    }
}</code>
Copy after login

You need to unmarshal the "payload" field into the appropriate data structure based on the "code" field.

Solution

The key here is to use the json.RawMessage type to delay the unmarshalling of the "payload" field until after you know its type. For example:

<code class="go">package main

import (
    "encoding/json"
    "fmt"
)

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

// Unmarshall into appropriate structures based on Code
func unmarshal(m []byte) error {
    var message Message
    err := json.Unmarshal(m, &message)
    if err != nil {
        return err
    }
    switch message.Code {
    case 3:
        var user User
        if err := json.Unmarshal(message.Payload, &user); err != nil {
            return err
        }
        fmt.Printf("Unmarshalled a User: %#v\n", user)
    case 4:
        var range Range
        if err := json.Unmarshal(message.Payload, &range); err != nil {
            return err
        }
        fmt.Printf("Unmarshalled a Range: %#v\n", range)
    default:
        return fmt.Errorf("unknown code: %d", message.Code)
    }
    return nil
}

func main() {
    json1 := []byte(`{"Code": 3, "Payload": {"ID": 1, "Pass": 1234}}`)
    if err := unmarshal(json1); err != nil {
        fmt.Printf("error: %v\n", err)
    }

    json2 := []byte(`{"Code": 4, "Payload": {"Start": 1, "End": 10}}`)
    if err := unmarshal(json2); err != nil {
        fmt.Printf("error: %v\n", err)
    }
}</code>
Copy after login

The above is the detailed content of How to Unmarshal Non-Homogenous JSON Data with a \'Code\' Field?. 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!