[英]can't unmarshal string into Go value of type struct
I run below javascript code. 我在javascript代码下面运行。
return $.ajax({
url: "/loyalty/api/rule/new",
type: "POST",
contentType: "application/json",
data: JSON.stringify({'rule':$('form').serializeObject(),'ruleId':ruleID(),'programId':parseInt(proID)})
});
and I use below code to decode it. 我使用下面的代码对其进行解码。
decoder := json.NewDecoder(r.Body)
var rules models.NewRule
err := decoder.Decode(&rules)
but then it gives below error message. 但随后却显示以下错误消息。
level=error msg="json: cannot unmarshal string into Go value of type models.NewRule" api="/rule/new" code=400 tenantid=7 username=admin
can you help me to fix this? 你能帮我解决这个问题吗?
my NewRule struct 我的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)
}
I think you're misunderstanding how serializeObject
works in JavaScript. 我认为您误会了serializeObject
在JavaScript中的工作方式。 From the fine manual : 从精美的手册中 :
.serializeObject — serializes the selected form into a JavaScript object .serializeObject —将所选表单序列化为JavaScript对象
$('form#contact').serializeObject(); //=> {user: {email: "jsmith@example.com", pets: ["cat", "dog"]}}
.serializeJSON — serializes the selected form into JSON .serializeJSON-将所选表单序列化为JSON
$('form#contact').serializeJSON(); //=> '{"user":{"email":"jsmith@example.com","pets":["cat","dog"]}}'
serializeObject
gives you an object so this: serializeObject
给您一个对象,因此:
{'rule': $('form').serializeObject(), 'ruleId': ruleID(), 'programId': parseInt(proID)}
will give you something like this JavaScript: 会给你这样的JavaScript:
{
rule: { /* some JavaScript object goes here */ },
ruleId: 6,
programId: 11
}
So the "rule"
key in the JSON will have a whole object (not a string) as its value and decoder.Decode
correctly refuses to unpack an object into a string. 因此,JSON中的"rule"
键会将整个对象(而不是字符串)作为其值和decoder.Decode
正确拒绝将对象解压缩为字符串。
If you want the rule
to be a string of JSON encoded data when you unpack it then you want JSON inside your JSON: 如果您希望rule
在解压缩时为JSON编码数据的字符串,则您希望JSON在JSON内:
data: JSON.stringify({
'rule': $('form').serializeJSON(), // <---- serialize the form to JSON, not an object
'ruleId': ruleID(),
'programId': parseInt(proID)
})
Then what you're doing should work and you'll end up with JSON encoded data in rules.Rule
in Go. 然后您正在做的事情应该会起作用,并且最终您将在rules.Rule
in Go中获得JSON编码的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.