[英]json: cannot unmarshal string into Go value of type main.test_struct
I receive a json from an api and i try to unmarshall it, and i don't understand the error that i get : 我从api收到一个json,我尝试将其解组,但我不明白我得到的错误:
json: cannot unmarshal string into Go value of type main.test_struct
json:无法将字符串解组为main.test_struct类型的Go值
Here is the json that i get : 这是我得到的json:
INFO: 2017/02/03 17:47:53 ApiRecordGeo.go:66: "{\\"lat\\":48.892423,\\"lng\\":2.215331,\\"acc\\":1962}"
here is my code : 这是我的代码:
type test_struct struct {
Lat float32 `json:"lat"`
Lng float32 `json:"lng"`
Acc int `json:"acc"`
}
func postGeo(w http.ResponseWriter, r *http.Request) {
var t test_struct;
err := json.NewDecoder(r.Body).Decode(&t)
if err != nil {
panic(err)
}
/* hah, err := ioutil.ReadAll(r.Body);
if err != nil {
panic(err)
}
Info.Println(hah)
s := string(hah)
Info.Println(s)
Info.Println(t.Lat)*/
defer r.Body.Close()
Info.Println("POST FP")
w.Header().Set("Access-Control-Allow-Origin", "*")
fmt.Fprintf(w, "200")
}
If anyone have any clue ... Thanks and regards 如果有人有任何线索...谢谢和问候
edit : Second version still the same error : 编辑:第二版本仍然相同的错误:
type test_struct struct {
Lat float32 `json:"lat"`
Lng float32 `json:"lng"`
Acc int `json:"acc"`
}
func postGeo(w http.ResponseWriter, r *http.Request) {
var t test_struct;
err := json.NewDecoder(r.Body).Decode(&t)
if err != nil {
panic(err)
}
/* hah, err := ioutil.ReadAll(r.Body);
if err != nil {
panic(err)
}
Info.Println(hah)
s := string(hah)
Info.Println(s)
Info.Println(t.Lat)*/
//defer r.Body.Close()
fmt.Println("POST FP")
w.Header().Set("Access-Control-Allow-Origin", "*")
fmt.Fprintf(w, "200")
}
edit ter : here si the code that send the data (in javascript) 编辑ter:这里si发送数据的代码(在javascript中)
var url = "https://www.googleapis.com/geolocation/v1/geolocate?key=666";
$.ajax({
type: 'POST',
url: url,
crossDomain: true,
success: function(data){
//success jsonp handler - assume content in data.response
console.log(data);
var long = data.location.lng ;
var lat = data.location.lat;
var params = {long:long, lat:lat};
url_bis = "http://localhost:9280/post_geo/";
$.ajax({
type: 'POST',
url: url_bis,
crossDomain: true,
data: params,
dataType: 'jsonp',
success: function(data2){
console.log(data2);
},
});
},
});
The tricky part is how the data is sent by a jQuery.ajax()
. 棘手的部分是
jQuery.ajax()
如何发送数据。 In a documentation you may find: 在文档中,您可能会发现:
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded".
默认情况下,作为对象传递给data选项的数据(从技术上讲,不是字符串)将被处理并转换为查询字符串,以适合默认的内容类型“ application / x-www-form-urlencoded” 。
Which means that data the script is sending looks more like: 这意味着脚本正在发送的数据看起来更像:
lat=48.892423&lng=2.215331&acc=1962
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.