[英]POST request to Jersey client cannot unmarshal JSON object that contains an empty array?
[英]Unmarshal json to a array from post request
見下面我的
main.go
type Data struct {
unit []string `json:"unit"`
}
func receive(w http.ResponseWriter, r *http.Request) {
dec := json.NewDecoder(r.Body)
for {
var d Data
if err := dec.Decode(&d); err == io.EOF {
break
} else if err != nil {
log.Println(err)
}
log.Printf("%s\n", d.unit)
}
}
引發的錯誤:“ json:無法將數組解組為main.Data類型的GO值”
moj.js
$(function(){
$('#start').on('click', function(){
var i;
var j = 0;
for (i = 0; i < result.length; i++){
if(result[i] == null){
}else if(result[i]==""){
}else{
lookup[j] = result[i];
j++
}
}
$.ajax({
type: 'POST',
url: '/start',
data: '[{"unit":"'+lookup+'"}]',
dataType: "json",
contentType: "application/json",
success: function () {
alert("Data posted.")
},
error: function(){
alert('Error posting data.')
}
});
});
});
我發送的“ json”如下所示:[{“ unit”:“ something”}]]。
在控制台中,我可以看到數據已像這樣發布。
兩件事情:
請參閱: https : //play.golang.org/p/4kfIQTXqYi
type Data struct {
Unit string `json:"unit"`
}
func receive(w http.ResponseWriter, r *http.Request) {
dec := json.NewDecoder(r.Body)
for {
var d []Data
if err := dec.Decode(&d); err == io.EOF {
break
} else if err != nil {
log.Println(err)
}
log.Printf("%s\n", d.Unit)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.