无法将字符串解组为struct类型的Go值

萨沙·亚历克斯(SashaAlex):

我在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)
}
亩太短:

我认为您误会了serializeObjectJavaScript的工作原理。精美的手册中

.serializeObject —将所选表单序列化为JavaScript对象

$('form#contact').serializeObject();
//=> {user: {email: "[email protected]", pets: ["cat", "dog"]}}

.serializeJSON-将所选表单序列化为JSON

$('form#contact').serializeJSON();
//=> '{"user":{"email":"[email protected]","pets":["cat","dog"]}}'

serializeObject给您一个对象,因此:

{'rule': $('form').serializeObject(), 'ruleId': ruleID(), 'programId': parseInt(proID)}

会给你这样的JavaScript:

{
    rule: { /* some JavaScript object goes here */ },
    ruleId: 6,
    programId: 11
}

因此,"rule"JSON中键将具有整个对象(而不是字符串)作为其值,并且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在Go中获得JSON编码的数据

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

json:无法将字符串解组为main.test_struct类型的Go值

得到:无法将字符串解组为Go值

无法将字符串解组为int64类型的Go值

json:无法将字符串解组为[] main.KVU类型的Go值

Golang-无法将数字解组为字符串类型的Go值

Docker返回“ json:无法将字符串解组为[] string类型的Go值”

json:无法将数组解组为struct类型的Go值

JSON无法将对象解组为字符串类型的GO值

无法将字符串解组到类型模型的Go struct字段Article.article_type中。

如何使用 go-mongo-driver 将 BSON 字符串值解组为自定义类型?

无法将字符串解组到Go struct字段中

json:无法将字符串解组到Go struct字段中

Go无法将字符串设置为struct

kubectl 返回不能将字符串解组为 map[string]interface {} 类型的 Go 值

无法在 Go 中将 !!seq 解组为字符串

json:无法将数组解组为main类型的Go值

如何使用go的json标签将数字和字符串属性解组为字符串值

golang:解组:json:无法将数组解组为main.MonitorServerInfo类型的Go值

无法将类型为“字符串”的值分配为类型为“ UILabel?”

将json数组解组到go struct中(数组位于JSON字符串的中间

如果将值为null的字符串编码的json int解组,则使用null之前的值

panic:json:无法将数组解组为main类型的Go值。

Terraform:“错误解码 JSON:json:无法将字符串解组到 Go struct 字段 ContainerDefinition”aws_ecs_task_definition 资源

始终将JSON解组为某些类型(字符串)

无法将布尔类型的值分配为字符串数据库表示形式

将GO YAML解组到地图或字符串

将JSON解组到struct:无法将数组解组到Go值

无法分配类型为'String'的值?键入“字符串”

将“ XML元素”解组为字符串属性