首页 > 解决方案 > 服务总线消息 反序列化 System.String 类型的对象时出错,但消息格式是正确的 json

问题描述

服务总线消息反序列化 System.String 类型的对象时出错,但消息格式是正确的 json。

使用代码向主题发送消息 -

 topicClient = new TopicClient(ServiceBusConnectionString, TopicName);

                // Create a new message to send to the topic.
                string messageBody = string.Format("{{ \"Id\":\"{0}\",\"Name\":\"{1}\" }}", "121", "Demo");
                var message = new Message(Encoding.UTF8.GetBytes(messageBody));

                // Send the message to the topic.
                await topicClient.SendAsync(message);

进入服务总线主题的消息看起来像 -

{ "Id":"121","Name":"Demo" }

从主题中读取消息时出现错误 -

string currentMessageData = currentMessage.GetBody<string>();

反序列化 System.String 类型的对象时出错。输入源的格式不正确。

标签: c#jsonazureservicebus

解决方案


我认为问题在于您的消息被写为 astream而不是 a string

代替

string currentMessageData = currentMessage.GetBody<string>();

尝试

Stream stream = message.GetBody<Stream>();
StreamReader reader = new StreamReader(stream);
string currentMessageData = reader.ReadToEnd();

推荐阅读