json - 有没有办法在golang中格式化这个json?

标签 json rest go webserver

我今天刚刚开始学习 GoLang,我正在尝试构建一个简单的 Rest API 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\",\"body\":\"This is a test body\",\"description\":\"This is a test\"}]"}

我希望正文只是 JSON 而不是字符串。我怎样才能实现这一目标?

最佳答案

bodyHttpResp 分开编码是没有意义的。相反,请将 Body 字段的类型更改为 interface{},然后将该字段设置为具体类型的任何值,而不是 json 字符串,例如[]Article,然后编码(marshal)一次响应。

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

关于json - 有没有办法在golang中格式化这个json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45889437/

相关文章:

java - 这是在 Java 中执行查询的好方法吗?

javascript - Websocket 上的错误处理是一个设计决策

android - 如何从 Android 应用程序调用 REST API?

go - 在 Go gin 中实现 IP 限制

go - Beego如何使用Casbin设置动态RBAC?

javascript - JSON 发送空数组

javascript - 动态构建 JSON-Data 和 JSONschema 的显示

c# - 在 C# 中向 json 对象添加属性

php - 分配自定义分类以使用 REST API 发布

go - BigQuery golang 客户端 : which context to use?