将消息传递给API时的Javascript对象编码/解码

我将消息传递给第三方消息队列,将消息中继到我的队列侦听器(全部在node.js服务器端)。 该消息具有预定义的格式,允许我定义“自定义属性”。 当我提供基本types(string,数字等)时,这工作正常,但是当我尝试并在自定义属性中传递对象时,它失败。

发送此消息:

var info = {foo: 100}; var message = { body: 'some string', customProperties: { type: 1, name: 'test', info: info } }; 

返回此消息:

 { body: 'some string', customProperties: { type: 1, name: 'test', info: '[object Object]' } }; 

并发送此消息:

 var info = {foo: 100}; var message = { body: 'some string', customProperties: { type: 1, name: 'test', info: JSON.stringify(info) } }; 

返回此消息:

 { body: 'some string', customProperties: { type: 1, name: 'test', info: '\\"{\\"foo\\":100}\\"' } }; 

当我尝试使用JSON.parse(customProperties.info)对其进行解码时,这会失败。 我认为发生的事情是,它是每个自定义属性调用.toString ? 任何想法如何在传递此消息时对一个简单对象进行编码/解码?

解决这个问题的一个解决scheme是以另一种格式对info进行编码,这种格式在Azure的ServiceBus中的setRequestHeaders()调用期间不会被修改。 你可以像你在第二个解决scheme中那样对JSON进行编码,但是你可以像这样Base64编码结果:

 var info = {foo: 100}; var message = { body: 'some string', customProperties: { type: 1, name: 'test', info: btoa(JSON.stringify(info)) } }; 

这将产生像这样的customProperties

 {type: 1, name: "test", info: "eyJmb28iOjEwMH0="} 

然后解码,你只需要做

 var info = JSON.parse(atob(message.customProperties.info)); 

这产生了

 {foo: 100}