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

无法将字符串解组为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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?