duanji7881 2019-02-23 13:51
浏览 43
已采纳

将结构编码为json Go

I have an issue encoding struct to json my code is

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))) }

the wanted result should be

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

I do not mind if it's "Marshal" or "encoding/json"

  • 写回答

3条回答 默认 最新

  • doujiang6944 2019-02-23 14:46
    关注

    To encode a struct to JSON string, there are three ways that provided by standard library :

    • Using Encoder which convert struct to JSON string, then write it to io.Writer. This one usually used if you want to send JSON data as HTTP request, or saving the JSON string to a file.
    • Using Marshal which simply convert struct to bytes, which can be easily converted to string.
    • Using MarshalIndent which works like Marshal, except it's also prettify the output. This is what you want for your problem right now.

    To compare between those three methods, you can use this code (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:
    " + string(btResult))
    
        // Using marshal
        btResult, _ = json.Marshal(&Test)
        fmt.Println("
    Using Marshal:
    " + string(btResult))
    
        // Using encoder
        var buffer bytes.Buffer
        json.NewEncoder(&buffer).Encode(&Test)
        fmt.Println("
    Using Encoder:
    " + buffer.String())
    }
    

    The output will look like this :

    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"}]}
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信