简体   繁体   English

当Golang的元帅转换为json时,数组部分变成了object,所以我想保留数组

[英]When converted to json by Golang's Marshal, the array part becomes an object, so I want to keep the array

What I want to do我想做的事

  • Convert {"color": "red", "mrkdwn_in":["text"]} in json to a structure with UnMarshal将 json 中的{"color": "red", "mrkdwn_in":["text"]}转换为具有 UnMarshal 的结构
  • Change "color" from 'red' to 'blue'将“颜色”从“红色”更改为“蓝色”
  • Change the changed structure to json with Marshal将更改后的结构更改为带有 Marshal 的 json
  • The original "mrkdwn_in":["text"]} is not well preserved.原始的"mrkdwn_in":["text"]}保存得不好。
    • It becomes "mrkdwn_in":[{"text":""}] or "mrkdwn_in":"" .它变成"mrkdwn_in":[{"text":""}]"mrkdwn_in":""
  • I want to keep the "mrkdwn_in" part in its original state.我想将“mrkdwn_in”部分保留在其原始 state 中。

code代码

package main

import (
    "encoding/json"
    "fmt"
)

type TestStruct struct {
    Color        string       `json:"color"`
    MrkdwnIn     []MrkdwnIn   `json:"mrkdwn_in"`
}

type MrkdwnIn struct {
    Text string `json:"text"`
}

func main() {
    jsonData1 := "{\"color\":\"red\",\"mrkdwn_in\":[\"text\"]}"
    var body TestStruct
    json.Unmarshal([]byte(jsonData1), &body)
    body.Color = "blue"
    var jsonData2 []byte
    jsonData2, _ = json.Marshal(body)

    jsonDataText := string(jsonData2)
    fmt.Println(jsonDataText)
}

Execution result of the above code上述代码的执行结果

在此处输入图像描述

The error is obvious错误很明显

MrkdwnIn     []MrkdwnIn   `json:"mrkdwn_in"`

MrkdwnIn is a array of object MrkdwnIn 是一个 object 的数组

MrkdwnIn     []string`json:"mrkdwn_in"`

MrkdwnIn should be a array of string MrkdwnIn 应该是一个字符串数组

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

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