将嵌套的结构体动态转换为嵌套的 JSON(使用 Golang)。

huangapple go评论85阅读模式
英文:

Convert a nested struct to nested json dynamically golang

问题

你可以使用encoding/json包来将嵌套的结构体转换为嵌套的JSON。首先,你需要为每个结构体定义JSON字段的标签,然后使用json.Marshal()函数将结构体转换为JSON字符串。

以下是你提供的示例结构体的修改版本,添加了JSON字段标签:

type Details struct {
    Name        string   `json:"name"`
    Age         int      `json:"age"`
    Address     *Address `json:"address"`
    DateOfBirth *Date    `json:"dateOfBirth"`
}

type Address struct {
    Street  string `json:"street"`
    City    string `json:"city"`
    State   string `json:"state"`
    Country string `json:"country"`
}

type Date struct {
    Day   int    `json:"day"`
    Month string `json:"month"`
    Year  int    `json:"year"`
}

type StudentDetails struct {
    Details *Details `json:"details"`
}

然后,你可以使用json.Marshal()函数将结构体转换为JSON字符串:

details := &Details{
    Name: "aaa",
    Age:  20,
    Address: &Address{
        Street:  "",
        City:    "",
        State:   "",
        Country: "",
    },
    DateOfBirth: &Date{
        Day:   1,
        Month: "Jan",
        Year:  2000,
    },
}

jsonData, err := json.Marshal(details)
if err != nil {
    // 错误处理
}

fmt.Println(string(jsonData))

输出将是以下JSON字符串:

{
    "name": "aaa",
    "age": 20,
    "address": {
        "street": "",
        "city": "",
        "state": "",
        "country": ""
    },
    "dateOfBirth": {
        "day": 1,
        "month": "Jan",
        "year": 2000
    }
}

你可以根据需要动态地构建结构体,并使用json.Marshal()将其转换为JSON字符串。

英文:

how do i convert the following nested struct

type Details struct {
    name        string
    age         int
    address     *address
    dateOfBirth *date
}

type address struct {
    street  string
    city    string
    state   string
    country string
}

type date struct {
    day   int
    month string
    year  int
}

type StudentDetails struct {
    details *PersonalDetails
}

to a nested json of any level in golang, something like this

{
    "Student_1":{
        "name":"aaa",
        "age":20,
        "address":[{
            "street":"",
            "city":"",
            "state":"",
            "country":""
        },{
            "street":"",
            "city":"",
            "state":"",
            "country":""
        }],
        "date":{
            "day":1,
            "month":"Jan",
            "year":2000
        }
    },
    "Student_2":{
        "name":"bbb",
        "age":22,
        "address":[{
            "street":"",
            "city":"",
            "state":"",
            "country":""
        },{
            "street":"",
            "city":"",
            "state":"",
            "country":""
        }],
        "date":{
            "day":1,
            "month":"Feb",
            "year":2002
        }
    }

}

i want to build a json dynamically based on what is in this struct. The struct is build from protocol buffer. The pointer points to the struct it needs to fetch the details from. I used to reflect package to access the struct, i'm able to read through the data but not able to build the same. Any help is appreciated

答案1

得分: 1

你应该构建对象,然后使用json.Marshal(obj)

解决方案可能如下所示:

package main

import (
	"encoding/json"
	"fmt"
)

type User struct {
	Name        string
	Age         int
	Active      bool
	lastLoginAt string
	Address     *address
}

type address struct {
	City   string
	Street string
}

func main() {
	u, err := json.Marshal(User{Name: "Bob", Age: 10, Active: true, lastLoginAt: "today", Address: &address{City: "London", Street: "some str."}})
	if err != nil {
		panic(err)
	}
	fmt.Println(string(u))
}

输出结果为:

{"Name":"Bob","Age":10,"Active":true,"Address":{"City":"London","Street":"some str."}}
英文:

You should construct the object and then use json.Marshal(obj)

The solution may be something like:

package main

import (
	"encoding/json"
	"fmt"
)

type User struct {
	Name        string
	Age         int
	Active      bool
	lastLoginAt string
	Address     *address
}

type address struct {
	City   string
	Street string
}

func main() {
	u, err := json.Marshal(User{Name: "Bob", Age: 10, Active: true, lastLoginAt: "today", Address: &address{City: "London", Street: "some str."}})
	if err != nil {
		panic(err)
	}
	fmt.Println(string(u))
}

The output is:

{"Name":"Bob","Age":10,"Active":true,"Address":{"City":"London","Street":"some str."}}

huangapple
  • 本文由 发表于 2022年6月24日 05:06:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/72736549.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定