[英]Converting string to json in Go
I am new to Go, and was learning to setup a http server.我是 Go 的新手,正在学习设置 http 服务器。 What i am trying to do is return a json output of 10 movies in my sql database.
我想做的是在我的 sql 数据库中返回 10 部电影的 json output。 But the resulting output isn't in json.
但生成的 output 不在 json 中。 I checked the output with online json formatters, and the output was in json format.
我用在线 json 格式化程序检查了 output,output 是 Z466DEEC76ECDF5FCA6D38ZZ571F6 格式。
I tried json.Marshall as well as json.Encode, but both are not giving the desired results.我尝试了 json.Marshall 和 json.Encode,但两者都没有给出预期的结果。
type movie_list struct {
Page int `json:"Page"`
Results []movie `json:"Results"`
}
type movie struct {
Id int `json:"Id"`
Title string `json:"Title"`
Language string `json:"Language"`
Release_date string `json:"Release_date"`
Poster_path string `json:"Poster_path"`
Background_path string `json:"Background_path"`
Overview string `json:"Overview"`
Genre_ids string `json:"Genre_ids"`
}
rows,err:=db.Query("select * from movies limit 10")
if err!=nil{
fmt.Println(err)
}
var list movie_list
var tag movie
for rows.Next(){
err:=rows.Scan(&tag.Id,&tag.Title,&tag.Language,&tag.Release_date,&tag.Poster_path,&tag.Background_path,&tag.Overview,&tag.Genre_ids)
if err != nil {
fmt.Println(err)
}
list.Results = append(list.Results,tag)
}
json.NewEncoder(w).Encode(list)
The ouput in postman - postman 中的输出 -
The formatted output -格式化后的 output -
my entire code is as follows (for reference)我的整个代码如下(供参考)
package main
import (
"fmt"
"log"
"net/http"
"encoding/json"
"database/sql"
_ "github.com/go-sql-driver/mysql"
"github.com/gorilla/mux"
"github.com/davecgh/go-spew/spew"
)
func handleRequests() {
myRouter := mux.NewRouter().StrictSlash(true)
myRouter.HandleFunc("/", homePage)
myRouter.HandleFunc("/movie/top_rated", returnSingleArticle)
log.Fatal(http.ListenAndServe(":10000", myRouter))
}
type movie_list struct {
Page int `json:"Page"`
Results []movie `json:"Results"`
}
type movie struct {
Id int `json:"Id"`
Title string `json:"Title"`
Language string `json:"Language"`
Release_date string `json:"Release_date"`
Poster_path string `json:"Poster_path"`
Background_path string `json:"Background_path"`
Overview string `json:"Overview"`
Genre_ids string `json:"Genre_ids"`
}
func homePage(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to the HomePage!")
fmt.Println("Endpoint Hit: homePage")
}
func returnSingleArticle(w http.ResponseWriter, r *http.Request) {
//vars := mux.Vars(r)
//key := vars["id"]
db, err := sql.Open("mysql", "root:72574484@tcp(127.0.0.1:3306)/PicturePerfect")
if err != nil {
fmt.Println(err)
}else{
fmt.Println("Connection Established")
}
rows,err:=db.Query("select * from movies limit 10")
if err!=nil{
fmt.Println(err)
}
var list movie_list
var tag movie
for rows.Next(){
err:=rows.Scan(&tag.Id,&tag.Title,&tag.Language,&tag.Release_date,&tag.Poster_path,&tag.Background_path,&tag.Overview,&tag.Genre_ids)
if err != nil {
fmt.Println(err)
}
fmt.Println(tag.Id)
s2, _ := json.Marshal(tag)
list.Results = append(list.Results,tag)
}
err = rows.Err()
if err != nil {
fmt.Println(err)
}
defer db.Close()
//fmt.Fprintf(w, "Hello, %q\n", list.Results[3])
json.NewEncoder(w).Encode(list)
spew.Dump(list)
//fmt.Fprintf(w, "given lamguage, %q\n", tag.Poster_path)
}
func main() {
handleRequests()
}
The problem is that the response content-type header is not application/json.问题是响应内容类型 header 不是 application/json。 Fix by setting the header before writing the body.
通过在写入正文之前设置 header 进行修复。
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(list)
If the content type is not specified by the application, then the net/http server calls http.DetectConentType to set the content type in the response header.如果应用程序没有指定内容类型,则 net/http 服务器调用http.DetectConentType来设置响应 header 中的内容类型。 The function does not detect JSON and defaults to text/plain.
function 不检测 JSON 并且默认为 text/plain。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.