Unmarshal partial data bytes into a custom structure

王林
Release: 2024-02-12 18:20:06
forward
517 people have browsed it

Unmarshal partial data bytes into a custom structure

Question content

I have data in the form of map[string][]byte, where key is the json field tag of the structure, value is a slice of bytes.

Consider this example:

type Tweet struct {
    UserId int `json:"user_id"`
    Message string `json:"message"`
}
Copy after login
data = {
"user_id":<some bytes>,
"message":<some bytes>
}
Copy after login

var t Tweet

How to unmarshal the corresponding field data into a Tweet structure, which can contain any type of field, i.e. slice/map/custom type/pointer type? Do I have to map each field's data individually one by one or is there any general way?

I tried marshalling the entire data and unmarshalling it back into a struct type, but it seems like it internally modifies the actual data and doesn't work.

bytes, err := json.Marshal(data)
var t Tweet
err = json.Unmarshal(bytes,&t)
Copy after login

Workaround

I don't think you mentioned your error, but the following worked for me. You can try this.

package main

import (
    "encoding/json"
    "fmt"
)

type Tweet struct {
    UserId  int    `json:"user_id"`
    Message string `json:"message"`
}

func main() {
    // Example data: map of field tags to JSON-encoded byte slices
    data := map[string]json.RawMessage{
        "user_id": []byte(`123`),             // Encoded as a JSON number
        "message": []byte(`"Hello, world!"`), // Encoded as a JSON string
    }

    // Convert map to JSON
    jsonData, err := json.Marshal(data)
    if err != nil {
        fmt.Println("Error marshalling map to JSON:", err)
        return
    }

    // Unmarshal JSON into Tweet struct
    var t Tweet
    if err := json.Unmarshal(jsonData, &t); err != nil {
        fmt.Println("Error unmarshalling JSON:", err)
        return
    }

    // Output the result
    fmt.Printf("Unmarshalled: %+v\n", t)

    // Marshal the Tweet struct back into JSON
    marshalledData, err := json.Marshal(t)
    if err != nil {
        fmt.Println("Error marshalling Tweet struct to JSON:", err)
        return
    }

    // Output the marshalled JSON
    fmt.Printf("Marshalled: %s\n", marshalledData)
}
Copy after login

The above is the detailed content of Unmarshal partial data bytes into a custom structure. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template