dongqie2028 2018-03-05 05:31
浏览 47
已采纳

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

I run below javascript code.

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

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)
}
  • 写回答

1条回答 默认 最新

  • dt20081409 2018-03-05 06:32
    关注

    I think you're misunderstanding how serializeObject works in JavaScript. From the fine manual:

    .serializeObject — serializes the selected form into a JavaScript object

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

    .serializeJSON — serializes the selected form into JSON

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

    serializeObject gives you an object so this:

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

    will give you something like this 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.

    If you want the rule to be a string of JSON encoded data when you unpack it then you want JSON inside your 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析