繁体   English   中英

编码结构为 json Go

[英]Encoding struct to json Go

我有一个问题编码结构到 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”

首先,我认为您在如何struct in go创建struct in go出错了,因为您可以轻松地将它们转换为 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查看

要将结构体编码为 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"}]}

如果您的目标只是将结果放入控制台,我无法bytes.Buffer您想要使用bytes.Buffer的观点。 假设重点是:

  1. 创建一个struct实例(对应一个JSON对象)
  2. 在屏幕上发射它

以下代码可以帮助您:

package main

import "encoding/json"
import "fmt"

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: []TestArray{
            TestArray{"test1"},
            TestArray{"test2"},
        },
    }

    res, _ := json.MarshalIndent(Test, "", "\t")
    fmt.Println(string(res))
}

json.MarshalIndent用于使结果格式化,如果你打扰它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM