如何在golang中将字符串转换为json?

时间:2019-06-10 07:58:40

标签: json string go

我想将字符串转换为Json并为其提供返回值。

通过POST请求(writePost)收到的c.JSON(200, string(body))值是:

  

“ {\” message \“:{\” @ type \“:\” response \“,\” @ service \“:\” service.community.cafe \“,\” @ version \“:\ “ 1.0.0 \”,\“状态\”:\“ 200 \”,\“结果\”:{\“ msg \”:\“成功\”,\“ url \”:\“ aaabcd \”, \“ articleId \”:211,\“ articleUrl \”:\“ https://abcde.com/abc/211 \”}}}“

// WriteResult Struct
type WriteResult struct {
    Message    int    `form:"msg" json:"msg"`
    URL        string `form:"url" json:"url"`
    ArticleID  int    `form:"articleId" json:"articleId"`
    ArticleURL string `form:"articleUrl" json:"articleUrl"`
}

func writePost(c *gin.Context) {
    var writeInfo WriteInfo

    if err := c.ShouldBind(&writeInfo); err != nil {
        fmt.Println("error : ", err)
    }

    url := "https://openapi.abcde.com/articles"

    var bearer = "Bearer " + writeInfo.AccessToken
    var bufs bytes.Buffer

    form := url.Values{}
    form.Add("subject", subject)
    form.Add("content", content)

    req, err := http.NewRequest("POST", url, strings.NewReader(form.Encode()))

    req.Header.Add("Authorization", bearer)
    req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    writeResult := new(WriteResult)
    body, _ := ioutil.ReadAll(resp.Body)
    c.JSON(200, string(body))
}

是否可以转换为Json并返回它?

谢谢您的建议。

1 个答案:

答案 0 :(得分:0)

在Go中非常简单

out, _ := json.Marshal(body)

请参见this答案。