【问题标题】:Is there a way to format this json in golang?有没有办法在golang中格式化这个json?
【发布时间】:2017-08-25 21:08:27
【问题描述】:

我今天刚开始学习GoLang,我正在尝试构建一个简单的Rest API Web服务器。

这是我想为每个请求发送到 Web 服务器的响应结构:

package main

type HttpResp struct{
    Status      int         `json:"status"`
    Description string      `json:"description"`
    Body        string      `json:"body"`
}

这是我的 articles.go 文件,它具有获取数据库中所有文章的功能:

package main

import (
    "encoding/json"
    "net/http"
    "log"
)

type Article struct{
    Id          string  `json:"id"`
    Title       string  `json:"title"`
    Body        string  `json:"body"`
    Description string  `json:"description"`
}

func AllArticles(w http.ResponseWriter, r *http.Request){
    log.Print("/articles - GET")
    db := connect()
    defer db.Close()

    var articles []Article
    results, err := db.Query("SELECT * FROM Articles")

    if err != nil{
        log.Print(err)
        return
    }

    for results.Next(){
        var article Article
        err = results.Scan(&article.Title, &article.Description, &article.Body, &article.Id)

        if err != nil{
            serr, _ := json.Marshal(err)
            json.NewEncoder(w).Encode(HttpResp{Status: 500, Description: "Failed to retrieve all articles", Body: string(serr)})
        }

        articles = append(articles, article)
    }   
    sarr, _ := json.Marshal(articles)

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(HttpResp{Status: 200, Body: string(sarr)})
}

我在这里面临的问题是响应是这样的:

{"status":200,"description":"","body":"[{\"id\":\"1\",\"title\":\"First\",\"正文\":\"这个 is a test body\",\"description\":\"This is a test\"}]"}

我希望正文只是 JSON 而不是字符串。我怎样才能做到这一点?

【问题讨论】:

  • 它只是双重编码,因为您的代码对其进行了双重编码。您将主体编码为 JSON,然后将该 JSON 放入另一个结构的字段中,然后将 that 编码为 JSON。如果你不这样做,你会得到你想要的结果。

标签: json rest go webserver


【解决方案1】:

bodyHttpResp 分开编组毫无意义。而是将Body 字段的类型更改为interface{},然后将该字段设置为具体类型的任何值,而不是json 字符串,例如[]Article 然后将响应编组一次。

type HttpResp struct{
    Status      int         `json:"status"`
    Description string      `json:"description"`
    Body        interface{} `json:"body"`
}

剩下的……

package main

import (
    "encoding/json"
    "net/http"
    "log"
)

type Article struct{
    Id          string  `json:"id"`
    Title       string  `json:"title"`
    Body        string  `json:"body"`
    Description string  `json:"description"`
}

func AllArticles(w http.ResponseWriter, r *http.Request){
    log.Print("/articles - GET")
    db := connect()
    defer db.Close()

    var articles []Article
    results, err := db.Query("SELECT * FROM Articles")

    if err != nil{
        log.Print(err)
        return
    }

    for results.Next(){
        var article Article
        err = results.Scan(&article.Title, &article.Description, &article.Body, &article.Id)

        if err != nil{
            serr, _ := json.Marshal(err)
            json.NewEncoder(w).Encode(HttpResp{Status: 500, Description: "Failed to retrieve all articles", Body: string(serr)})
        }

        articles = append(articles, article)
    }

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(HttpResp{Status: 200, Body: articles})
}

【讨论】:

  • 是的!谢谢 !我大概是 4 小时前开始学习它,但还没有了解接口类型,我会去阅读一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-22
  • 2017-03-29
相关资源
最近更新 更多