[英]json: cannot unmarshal string into Go value of type main.test_struct
[英]can't unmarshal string into Go value of type struct
我在javascript代碼下面運行。
return $.ajax({
url: "/loyalty/api/rule/new",
type: "POST",
contentType: "application/json",
data: JSON.stringify({'rule':$('form').serializeObject(),'ruleId':ruleID(),'programId':parseInt(proID)})
});
我使用下面的代碼對其進行解碼。
decoder := json.NewDecoder(r.Body)
var rules models.NewRule
err := decoder.Decode(&rules)
但隨后卻顯示以下錯誤消息。
level=error msg="json: cannot unmarshal string into Go value of type models.NewRule" api="/rule/new" code=400 tenantid=7 username=admin
你能幫我解決這個問題嗎?
我的NewRule結構
type NewRule struct {
TenantID int `db:"tenantId"json:"tenantId"`
ProgramID commons.NullInt64 `db:"programId"json:"programId"`
RuleID commons.NullInt64 `db:"ruleId"json:"ruleId"`
Rule commons.NullString `db:"rule"json:"rule"`
}
func (p NewRule) String() string {
b, _ := json.Marshal(p)
return string(b)
}
我認為您誤會了serializeObject
在JavaScript中的工作方式。 從精美的手冊中 :
.serializeObject —將所選表單序列化為JavaScript對象
$('form#contact').serializeObject(); //=> {user: {email: "jsmith@example.com", pets: ["cat", "dog"]}}
.serializeJSON-將所選表單序列化為JSON
$('form#contact').serializeJSON(); //=> '{"user":{"email":"jsmith@example.com","pets":["cat","dog"]}}'
serializeObject
給您一個對象,因此:
{'rule': $('form').serializeObject(), 'ruleId': ruleID(), 'programId': parseInt(proID)}
會給你這樣的JavaScript:
{
rule: { /* some JavaScript object goes here */ },
ruleId: 6,
programId: 11
}
因此,JSON中的"rule"
鍵會將整個對象(而不是字符串)作為其值和decoder.Decode
正確拒絕將對象解壓縮為字符串。
如果您希望rule
在解壓縮時為JSON編碼數據的字符串,則您希望JSON在JSON內:
data: JSON.stringify({
'rule': $('form').serializeJSON(), // <---- serialize the form to JSON, not an object
'ruleId': ruleID(),
'programId': parseInt(proID)
})
然后您正在做的事情應該會起作用,並且最終您將在rules.Rule
in Go中獲得JSON編碼的數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.