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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度