使用Json.Net序列化包含反斜杠的字符串

时间:2014-08-05 08:09:42

标签: c# escaping json.net

我正在尝试将包含UNC-Windows路径的对象序列化为共享资源。

我的代码:

     public class NetworkConnection
     {
        public String LocalName { get; private set; }
        public String RemotePath { get; private set; }
        public String ResourceType { get; private set; }

        private NetworkConnection()
        {
            LocalName = String.Empty;
            RemotePath = String.Empty;
            ResourceType = String.Empty;
        }

        public static List<NetworkConnection> getNetworkConnections()
        {
            try
            {
                List<NetworkConnection> networkConnections = new List<NetworkConnection>();
                ManagementObjectSearcher searcher =
                    new ManagementObjectSearcher("select * from Win32_NetworkConnection");
                foreach (var item in searcher.Get())
                {
                    NetworkConnection con = new NetworkConnection();
                    con.LocalName = (string) (item.GetPropertyValue("LocalName") ?? String.Empty);

                    con.RemotePath = (string)(item.GetPropertyValue("RemotePath") ?? String.Empty);
                    Uri uri = new Uri(con.RemotePath);
                    con.RemotePath = uri.AbsoluteUri.Replace("file://", @"\");
                    con.RemotePath = con.RemotePath.Replace('/', '\\');
                    con.ResourceType = (string) (item.GetPropertyValue("ResourceType") ?? String.Empty);

                    networkConnections.Add(con);
                }
                return networkConnections;
            }
            catch (Exception)
            {
                return new List<NetworkConnection>();
            }
        }
    }

   class PC
    {
        public Software.Software Software { get; private set; }
        public Hardware.Hardware Hardware { get; private set; }
        public PC()
        {
            Software = new Software.Software();
            Hardware = new Hardware.Hardware();
        }
    }

    public class Hardware
        {
            public List<NetworkConnection> NetworkConnections { get; private set; } 
            public Hardware()
            {
                NetworkConnections = NetworkConnection.getNetworkConnections();
            }
        }

//Serialising
       PC pc = new PC();
       using (StreamWriter writer = new StreamWriter("deimama.txt"))
       {
           writer.WriteLine(JsonConvert.SerializeObject(pc, Formatting.Indented));
       }

输出(缩短):

\\192.168.1.1\\speech

通缉输出:

\\192.168.1.1\speech

PS:我尝试了不同的字符串替换方法

0 个答案:

没有答案