dounei9043 2016-05-18 08:47
浏览 56
已采纳

Json解组因字符无效而失败

Im having difficulties to unmarshal json content in golang. One of the fields in my object contains xml content and occasionally it will fail, claiming messages such as: invalid character '\x..' in string literal

I understand that this is as a result of control characters in my xml, but dont know how to handle it. I store my documents in mongoosejs and save the xml field as type String My struct Im trying to deserialize to is declared this way:

type A struct {
  Xml []byte `json:"xml"`
}

Unmarshaling is done the following way:

var xml A
err := json.Unmarshal(content, &xml)
  • 写回答

2条回答 默认 最新

  • dqbr37828 2016-05-18 15:15
    关注

    Since JSON cannot contain any control characters, I found the most convenient solution to simply convert the xml data to base64, e.g:

    // before sending in javascript
    a.xml = new Buffer(a.xml).toString('base64')
    

    Then, In golang side:

    // Declare a new type for custom unmarshaling
    type XmlB64 []byte
    func (b *XmlB64) UnmarshalJSON(data []byte) error {
        if b == nil {
            return fmt.Errorf("UnmarshalJSON on nil pointer")
        }
    
        if len(data) == 0 {
            return nil
        }
    
        if x, err := base64.StdEncoding.DecodeString(string(data)); err != nil {
            return err
        } else {
            *b = x
        }
    
        return nil
    }
    

    After doing that, Unmarshalling base64 content is done without doing anything special in the code. We first change our struct:

    type A struct {
      Xml XmlB64 `json:"xml"`
    }
    

    Unmarshal:

    var xml A
    err := json.Unmarshal(content, &xml)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源