将包含特殊字符的嵌套json字符串反序列化为对象

时间:2016-06-20 21:03:20

标签: c# json.net deserialization

我有用户发送可能包含任何特殊字符的邮件。我把那些数据作为json字符串。我试图将字符串反序列化为一个对象,然后将其传递给我的webapi。

但是,我无法成功反序列化数据。我创建了一个简单的c#控制台应用程序来测试这个函数。

public class Program
{
    public static void Main()
    {            
        Console.WriteLine("Enter input:"); 
        string data = Console.ReadLine(); 

        // One of the SO article says,
        // If the JSON is created using a JSON serializer, then all the
        // special characters will be escaped properly
        var sData = JsonConvert.SerializeObject(data);     

        MappedData mappedData = JsonConvert.DeserializeObject<MappedData>(dData.ToString());

        Console.WriteLine(mappedData.PostData); //these need to be posted to webapi
        Console.ReadKey();
    }
}
public class MappedData
{
    [JsonProperty("PostData")]
    public string PostData { get; set; }

    [JsonProperty("MessageQueueInformation")]
    public string MessageQueueInformation { get; set; }
}

文章提到:enter link description here

有效的测试数据(无特殊字符): { "MessageQueueInformation": '{"EntityId":"13","Action":"Add"}', "PostData": '{"listMessage":[{"message":"Successful case 1"}]}'}

此操作失败,错误为:Bad JSON escape sequence: \,.

{ "MessageQueueInformation": '{"EntityId":"13","Action":"Add"}', "PostData": '{"listMessage":[{"message":"Unsuccessful case- aaa /, \, ^, &amp;, %, #'/"\\\,''!~"}]}'}

1 个答案:

答案 0 :(得分:0)

您的代码很好,但您的用户需要将他发送的消息更改为实际上是JSON。 JSON输入需要正确编码。

  • 如果您希望\出现在字符串中,那么在JSON字符串中它将显示为\\
  • 如果您希望"出现在字符串中,则它应显示为\"
  • 如果您希望'出现在字符串中,则该字符应显示为\'

{ "MessageQueueInformation": '{"EntityId":"13","Action":"Add"}', "PostData": '{"listMessage":[{"message":"Unsuccessful case- aaa /, \\, ^, &amp;, %, #'/\"\\\\\\,\'\'!~"}]}'}

相关问题