无法反序列化当前 JSON 对象,因为该类型需要一个 JSON 数组
Cannot deserialize the current JSON object because the type requires a JSON array
问题:我错过了什么?任何指导将不胜感激。
场景:我正在尝试收集表单数据并使用 API 来验证地址。
问题: 无法反序列化当前 JSON 对象。
类似的帖子:
- Cannot deserialize the current JSON array (e.g. [1,2,3])
- Getting "because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly" error when deserializing a Json object
错误:
Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[ShipEngine.Api.Contracts.Shared.Addresses.Address]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
代码:
package main
import (
"fmt"
"log"
"encoding/json"
"net/http"
"strings"
"io/ioutil"
)
type Address struct {
Address1 string `json:"address_line1"`
Address2 string `json:"address_line2"`
City string `json:"city_locality"`
State string `json:"state_province"`
Postal string `json:"postal_code"`
Country string `json:"country_code"`
}
func home(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.Error(w, "404 not found.", http.StatusNotFound)
return
}
switch r.Method {
case "GET":
http.ServeFile(w, r, "form.html")
case "POST":
// Call ParseForm() to parse the raw query and update r.PostForm and r.Form.
if err := r.ParseForm(); err != nil {
fmt.Fprintf(w, "ParseForm() err: %v", err)
return
}
fmt.Fprintf(w, "Post from website! r.PostFrom = %v\n", r.PostForm)
address1 := r.FormValue("address1")
address2 := r.FormValue("address2")
city := r.FormValue("city")
state := r.FormValue("state")
postal := r.FormValue("postal")
country := r.FormValue("country")
fmt.Fprintf(w, "Address1 = %s\n", address1)
fmt.Fprintf(w, "Address2 = %s\n", address2)
fmt.Fprintf(w, "City = %s\n", city)
fmt.Fprintf(w, "State = %s\n", state)
fmt.Fprintf(w, "Postal = %s\n", postal)
fmt.Fprintf(w, "Country = %s\n", country)
// u1 := User{1, "John Doe", "gardener"}
address := Address{
Address1: address1,
Address2: address2,
City: city,
State: state,
Postal: postal,
Country: country,
}
json_data, err := json.Marshal(address)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(json_data))
fmt.Fprintf(w, "JSON = %s\n", string(json_data))
url := "https://api.shipengine.com/v1/addresses/validate"
method := "POST"
payload := strings.NewReader(string(json_data))
client := &http.Client {}
req, err := http.NewRequest(method, url, payload)
if err != nil {
fmt.Println(err)
}
req.Header.Add("Host", "api.shipengine.com")
req.Header.Add("API-Key", "INSERT_SECRET_KEY")
req.Header.Add("Content-Type", "application/json")
res, err := client.Do(req)
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
fmt.Println(string(body))
default:
fmt.Fprintf(w, "Sorry, only GET and POST methods are supported.")
}
}
func main() {
http.HandleFunc("/", home)
fmt.Printf("Starting server for testing HTTP POST...\n")
if err := http.ListenAndServe(":80", nil); err != nil {
log.Fatal(err)
}
}
Ship Engine address validation API 需要一个地址数组来验证。使用此代码在请求中生成一个 JSON 数组:
json_data, err := json.Marshal([]*Address{&address})
并不是说这与问题有关,但您可以使用以下代码创建请求主体来消除不必要的内存分配:
payload := bytes.NewReader(json_data)
看来您发送的是单个对象而不是数组。
在此处查看预期的有效负载:https://www.shipengine.com/docs/addresses/validation/
问题:我错过了什么?任何指导将不胜感激。
场景:我正在尝试收集表单数据并使用 API 来验证地址。
问题: 无法反序列化当前 JSON 对象。
类似的帖子:
- Cannot deserialize the current JSON array (e.g. [1,2,3])
- Getting "because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly" error when deserializing a Json object
错误:
Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[ShipEngine.Api.Contracts.Shared.Addresses.Address]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
代码:
package main
import (
"fmt"
"log"
"encoding/json"
"net/http"
"strings"
"io/ioutil"
)
type Address struct {
Address1 string `json:"address_line1"`
Address2 string `json:"address_line2"`
City string `json:"city_locality"`
State string `json:"state_province"`
Postal string `json:"postal_code"`
Country string `json:"country_code"`
}
func home(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.Error(w, "404 not found.", http.StatusNotFound)
return
}
switch r.Method {
case "GET":
http.ServeFile(w, r, "form.html")
case "POST":
// Call ParseForm() to parse the raw query and update r.PostForm and r.Form.
if err := r.ParseForm(); err != nil {
fmt.Fprintf(w, "ParseForm() err: %v", err)
return
}
fmt.Fprintf(w, "Post from website! r.PostFrom = %v\n", r.PostForm)
address1 := r.FormValue("address1")
address2 := r.FormValue("address2")
city := r.FormValue("city")
state := r.FormValue("state")
postal := r.FormValue("postal")
country := r.FormValue("country")
fmt.Fprintf(w, "Address1 = %s\n", address1)
fmt.Fprintf(w, "Address2 = %s\n", address2)
fmt.Fprintf(w, "City = %s\n", city)
fmt.Fprintf(w, "State = %s\n", state)
fmt.Fprintf(w, "Postal = %s\n", postal)
fmt.Fprintf(w, "Country = %s\n", country)
// u1 := User{1, "John Doe", "gardener"}
address := Address{
Address1: address1,
Address2: address2,
City: city,
State: state,
Postal: postal,
Country: country,
}
json_data, err := json.Marshal(address)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(json_data))
fmt.Fprintf(w, "JSON = %s\n", string(json_data))
url := "https://api.shipengine.com/v1/addresses/validate"
method := "POST"
payload := strings.NewReader(string(json_data))
client := &http.Client {}
req, err := http.NewRequest(method, url, payload)
if err != nil {
fmt.Println(err)
}
req.Header.Add("Host", "api.shipengine.com")
req.Header.Add("API-Key", "INSERT_SECRET_KEY")
req.Header.Add("Content-Type", "application/json")
res, err := client.Do(req)
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
fmt.Println(string(body))
default:
fmt.Fprintf(w, "Sorry, only GET and POST methods are supported.")
}
}
func main() {
http.HandleFunc("/", home)
fmt.Printf("Starting server for testing HTTP POST...\n")
if err := http.ListenAndServe(":80", nil); err != nil {
log.Fatal(err)
}
}
Ship Engine address validation API 需要一个地址数组来验证。使用此代码在请求中生成一个 JSON 数组:
json_data, err := json.Marshal([]*Address{&address})
并不是说这与问题有关,但您可以使用以下代码创建请求主体来消除不必要的内存分配:
payload := bytes.NewReader(json_data)
看来您发送的是单个对象而不是数组。 在此处查看预期的有效负载:https://www.shipengine.com/docs/addresses/validation/