登录
首页 >  Golang >  Go问答

使用 Go 将 struct 编码为 JSON

来源:stackoverflow

时间:2024-02-29 14:30:31 439浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《使用 Go 将 struct 编码为 JSON》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

我在将结构编码为 json 时遇到问题,我的代码是

type mainstructure struct {
    text  string      json:"text,omitempty"
    array []testarray json:"test_array,omitmepty"
}

type testarray struct { arraytext string json:"array_text,omitempty" }

func main() { test := mainstructure{ text: "test", array: [ { arraytext: "test1" }, { arraytext: "test2" } ] } body := new(bytes.buffer) json.newencoder(body).encode(&test) fmt.println(string([]byte(body))) }

想要的结果应该是

{
    "text": "test",
    "test_array": [
        {
            "array_text": "test1"
        },
        {
            "array_text": "test2"
        }
    ]
}

我不介意它是“marshal”还是“encoding/json”


解决方案


要将结构体编码为 json 字符串,标准库提供了三种方法:

  • 使用Encoder将struct转换为json字符串,然后将其写入io.writer。如果您想将 json 数据作为 http 请求发送,或将 json 字符串保存到文件中,通常会使用此方法。
  • 使用 Marshal 简单地将结构体转换为字节,字节可以轻松转换为字符串。
  • 使用 MarshalIndent,其工作方式类似于 marshal,只不过它还可以美化输出。这就是您现在想要解决的问题。

要比较这三种方法,您可以使用以下代码 (Go Playground):

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
)

type mainstructure struct {
    text  string      `json:"text,omitempty"`
    array []testarray `json:"test_array,omitempty"`
}

type testarray struct {
    arraytext string `json:"array_text,omitempty"`
}

func main() {
    test := mainstructure{
        text: "test",
        array: []testarray{
            {arraytext: "test1"},
            {arraytext: "test2"},
        },
    }

    // using marshal indent
    btresult, _ := json.marshalindent(&test, "", "  ")
    fmt.println("using marshal indent:\n" + string(btresult))

    // using marshal
    btresult, _ = json.marshal(&test)
    fmt.println("\nusing marshal:\n" + string(btresult))

    // using encoder
    var buffer bytes.buffer
    json.newencoder(&buffer).encode(&test)
    fmt.println("\nusing encoder:\n" + buffer.string())
}

输出将如下所示:

using marshal indent:
{
  "text": "test",
  "test_array": [
    {
      "array_text": "test1"
    },
    {
      "array_text": "test2"
    }
  ]
}

using marshal:
{"text":"test","test_array":[{"array_text":"test1"},{"array_text":"test2"}]}

using encoder:
{"text":"test","test_array":[{"array_text":"test1"},{"array_text":"test2"}]}

首先,我认为您在如何在 go 中创建 struct 上出错了,因为您可以轻松地将它们转换为 json。

您应该首先创建一个正确的结构,然后执行 json.marshal(test) 将其转换为正确的 json,例如:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {

    type TestArray struct {
        ArrayText string `json:"array_text,omitempty"`
    }
    type MainStructure struct {
        Text  string      `json:"text,omitempty"`
        Array []TestArray `json:"test_array,omitmepty"`
    }

    Test := MainStructure{
        Text: "test",
        Array: []TestArray{
            TestArray{ArrayText: "test1"},
            TestArray{ArrayText: "test2"},
        }}
    bytes, err := json.Marshal(Test)
    if err != nil {
        fmt.Println("eror marshalling")
    } else {
        fmt.Println(string(bytes))
    }
}

请拨打 play.golang.org 查看此内容

本篇关于《使用 Go 将 struct 编码为 JSON》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>