Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Json Golang API的编码问题_Json_Rest_Go - Fatal编程技术网

Json Golang API的编码问题

Json Golang API的编码问题,json,rest,go,Json,Rest,Go,我正试图通过golang使用JSON API,但在获得响应时遇到了麻烦。我使用的是一个示例JSON端点,返回 { "userId": 1, "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\

我正试图通过golang使用JSON API,但在获得响应时遇到了麻烦。我使用的是一个示例JSON端点,返回

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
这是我的代码,来自:

这是输出:

go run main.go 
&{200 OK 200 HTTP/1.1 1 1 map[Cf-Cache-Status:[HIT] Cf-Ray:[2bf857d2e55e0d91-SJC] Access-Control-Allow-Credentials:[true] Cache-Control:[public, max-age=14400] Expires:[Sat, 09 Jul 2016 06:28:31 GMT] X-Content-Type-Options:[nosniff] Server:[cloudflare-nginx] Date:[Sat, 09 Jul 2016 02:28:31 GMT] Connection:[keep-alive] X-Powered-By:[Express] Etag:[W/"124-yv65LoT2uMHrpn06wNpAcQ"] Content-Type:[application/json; charset=utf-8] Set-Cookie:[__cfduid=d0c4aacaa5db8dc73c59a530f3d7532af1468031311; expires=Sun, 09-Jul-17 02:28:31 GMT; path=/; domain=.typicode.com; HttpOnly] Pragma:[no-cache] Via:[1.1 vegur] Vary:[Accept-Encoding]] 0xc8200ee100 -1 [chunked] false map[] 0xc8200da000 <nil>}
go运行main.go
&{200 OK 200 HTTP/1.1 1 1 map[Cf Cache Status:[HIT]Cf Ray:[2BF85D2E55E0D91 SJC]访问控制允许凭据:[true]缓存控制:[public,max age=14400]过期:[Sat,2016年7月9日06:28:31 GMT]X-Content-Type-Options:[nosniff]服务器:[cloudflare nginx]日期:[Sat,2016年7月9日02:28:31 GMT]连接:[keep alive]X-Powered-By:[Express]Etag:[W/“124-YV65LOT2 UMHRPN06WNPACQ”]内容类型:[application/json;charset=utf-8]集Cookie:[uuuu cfduid=d0c4aacaa5db8dc73c59a530f3d7532af1468031311;expires=Sun,09-Jul-17 02:28:31 GMT;path=/;domain=.typicode.com;HttpOnly]Pragma:[无缓存]Via:[1.1.1 vegur]Vary:[接受编码]]0xc8200ee100-1[chunked]假映射[]0xc8200da000}
我知道端点可以工作。这是编码问题还是其他问题?我在Mac OSX 10.11.15上


谢谢

您在解组时出错:
如果您打印错误,则无法将数字解组为字符串类型的Go值。UserId和Id应为int

请不要忽略错误

请尝试以下代码:

package main

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

type Post struct {
    UserID int
    ID     int
    Title  string
    Body   string
}

func getJson(url string, target interface{}) error {
    r, err := http.Get(url)
    if err != nil {
        return err
    }
    defer r.Body.Close()
    fmt.Println(r)
    return json.NewDecoder(r.Body).Decode(target)
}

func main() {
    post := new(Post) // or &Foo{}
    err := getJson("http://jsonplaceholder.typicode.com/posts/1", &post)
    if err != nil {
        panic(err)
    }

    println(post.Body)
    fmt.Printf("Post: %+v\n", post)
}
编辑: 为什么我不能打印出响应正文的内容并在命令行中看到它?它是编码的吗? Ans:HTTP请求或响应过去采用响应头字段定义的格式或编码

通过解码可能已应用的任何传输编码以确保消息的安全和正确传输,从消息体获得响应体

如果您打印:
fmt.Println(“标题:%#v\n”,r.Header)


您将看到,
内容类型:[application/json;charset=utf-8]
这就是您使用json解码的原因。它也可以是xml。

也许您应该尝试以下方法:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)   

type Result struct {
    UserID int    `json:"userId"`
    ID     int    `json:"id"`
    Title  string `json:"title"`
    Body   string `json:"body"`
}   

func main() {

    url := "http://jsonplaceholder.typicode.com/posts/1"

    req, _ := http.NewRequest("GET", url, nil)

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

    var result Result
    err := json.Unmarshal(body, &result)
    if err != nil {
        fmt.Println(err)
    }   

    fmt.Println(res)
    fmt.Println(string(body))

    fmt.Println(result)
    //fmt.Println(result.Title)
    //fmt.Println(result.Body)
}

您将得到一个结果结构

谢谢。非常有用。快速跟进问题:为什么我不能打印响应正文的内容并在命令行中查看它?它是否已编码?我实际上认为这是一个笑话,取笑忽略错误:)
package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)   

type Result struct {
    UserID int    `json:"userId"`
    ID     int    `json:"id"`
    Title  string `json:"title"`
    Body   string `json:"body"`
}   

func main() {

    url := "http://jsonplaceholder.typicode.com/posts/1"

    req, _ := http.NewRequest("GET", url, nil)

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

    var result Result
    err := json.Unmarshal(body, &result)
    if err != nil {
        fmt.Println(err)
    }   

    fmt.Println(res)
    fmt.Println(string(body))

    fmt.Println(result)
    //fmt.Println(result.Title)
    //fmt.Println(result.Body)
}