简体   繁体   中英

C# Deserialize JSON with chars '/' using JavaScriptSerializer

I've got such JSON string:

 "[{\"macId\":\"ttsh\",\"modelNumber\":\"tshf\"},{\"macId\":\"dtgstr\",\"modelNumber\":\"drtgsdsrtg\"}]"

I want to Deserialize it. What I'm doing:

    private static IList<HandsetModel> handsetsList = new List<HandsetModel>();
    handsetsList = new JavaScriptSerializer().Deserialize<List<HandsetModel>>(handsetsJson);

public sealed class HandsetModel
{
    public string macId { get; set; }

    public string modelNumber { get; set; }
}

What I've tryed to do with string:

handsetsJson = handsetsJson.Replace(@"\", "");

But this line didn't help me. May anybody help?

From memory, I believe there are several things you can do to clean this up:

One route is something like:

 public static string CleanAllWhiteSpace(string messyJson)
        {
            return (Regex.Replace(messyJson, @"(\s)+|(\n)+|(\r)+|(\t)+", ""));
        }

        public static string removeEscapedQuotes(string escapedString)
        {
            return (Regex.Replace(escapedString, "\\\"", "\""));
        }

Another thought, again from memory is use NewtonSoft.JSON instead of the .NET native implementation as it seems like it serialized/ deserialized more cleanly/ predictably.

For example with NewtonSoft's:

string serial = JsonConvert.SerializeObject(s).ToString();

I get a nice clean:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM