我试图对来自MSMQ的json消息进行deseriliaze,但是在解析时会出现异常。
我这样做:
var transaction = new MessageQueueTransaction();
transaction.Begin();
Console.WriteLine("Listening For Message Now...");
var message = queue.Receive(transaction);
var reader = new StreamReader(message.BodyStream,Encoding.Default);
var jsonMessage = reader.ReadToEnd();
var emailMessage = JsonConvert.DeserializeObject<MessageType>(jsonMessage);
The Exception:
................
Json Parser Exception Unexpected character encountered while parsing value: S. Path '', line 0, position 0
The Message Coming from MSMQ with control characters:
.................................
我认为这次尝试是解析时的一般性考察。
从队列接收消息的正确方法是什么?
很高兴得到一些有意义的例子:)
答案 0 :(得分:1)
A formatter must be set before and after. Here's what I mean:
MessageQueue mq = new MessageQueue(@".\private$\<YourQueue>");
using (MessageQueueTransaction mqt = new MessageQueueTransaction())
{
mqt.Begin();
message = new Message();
message.Formatter = new XmlMessageFormatter(new Type[] { typeof(String) });
message.Body = JsonConvert.SerializeObject(<YourJsonObject>);
mq.Send(message, mqt);
mqt.Commit();
}
Then you read the message like this:
transaction = new MessageQueueTransaction();
using (MessageQueue mq = new MessageQueue(<YourQueue>)
{
transaction.Begin();
mq.Formatter = new XmlMessageFormatter(new Type[] { typeof(String) });
Message m = mq.Receive(100, transaction);
YourObjectType o = JsonConvert.DeserializeObject<YourObjectType>(m.Body.ToString());
}
transaction.Commit();