.net 将对象序列化成字符串,出现转义符问题

.net 将对象序列化成字符串,出现转义符问题

问题出现原因:

如果出现转义符,一般是因为进行了两次序列化才导致这样的情况的,也就是说,内层某个key的value已经序列化成字符串了,

外层再次序列化的时候,又对内层进行了第二次序列化,所以导致内层的属性或者说是键值对,出现了转义符。

解决办法:

内层的key-value中的value如果是一个对象,就先不要使用 string entityListJson = JsonConvert.SerializeObject(retrunEntitieList) 进行序列化,

而是直接使用没有做过转换的原对象进行赋值,或者 JArray jArray = JArray.FromObject(retrunEntitieList) 转换成json数组

            //打印json内容到本地文件 
            List<RetrunEntity> retrunEntitieList = new List<RetrunEntity>();
            for (int i = 0; i < 2; i++)
            {
                RetrunEntity retrunEntityObj = new RetrunEntity
                {
                    bank_type = "type_" + i,
                    transaction_id = "id_" + i
                };
                retrunEntitieList.Add(retrunEntityObj);
            }
            //json数组
            JArray jArray = JArray.FromObject(retrunEntitieList);
            //json字符串
            string entityListJson = JsonConvert.SerializeObject(retrunEntitieList);

            Dictionary<string, object> map = new Dictionary<string, object>
            {
                ["Json"] = entityListJson,//json字符串赋值,最后的外层对象打印有转义符
                ["JArray"] = jArray,//json数组赋值,最后的外层对象打印不带转义符
                ["Entity"] = retrunEntitieList[0],//单个实体对象赋值,最后的外层对象打印不带转义符
                ["EntityList"] = retrunEntitieList,//多个实体对象赋值,最后的外层对象打印不带转义符
                ["templateMessage"] = "456",
                ["sign"] = "XZFZF"
            };
            //将字典类型序列化为json字符串
            string requestData = "[" + SerializeDictionaryToJsonString(map) + "]";
            Console.WriteLine(requestData);
            Console.WriteLine();
            var path = @"D:\用户目录\桌面\json打印内容.txt";
            WriteMessageToFile(path, requestData);

            var jobjectResult = new JObject
            {
                ["Json"] = entityListJson,//json字符串赋值,最后的外层对象打印有转义符
                ["JArray"] = jArray,//json数组赋值,最后的外层对象打印不带转义符
                ["Status"] = 1
            };
            string resultString = jobjectResult.ToString();
            Console.WriteLine(resultString);
            Console.WriteLine();
            
            WriteMessageToFile(path, resultString);
            Console.ReadKey();

            #region----反面教材----
            //打印出来的结果有转义符
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            JsonWriter writer = new JsonTextWriter(sw);
            writer.WriteStartObject();
            writer.WritePropertyName("Status");
            writer.WriteValue(1);
            writer.WritePropertyName("Goods");
            writer.WriteValue(jArray.ToString());
            writer.WriteEndObject();
            writer.Flush();
            Console.WriteLine(sb.ToString());
            Console.WriteLine();
            Console.WriteLine(entityListJson);
            Console.WriteLine();
            #endregion----反面教材----

 

        /// <summary>
        /// 输出指定信息到文本文件
        /// </summary>
        /// <param name="path">文本文件路径:D:\用户目录\桌面\json打印内容.txt</param>
        /// <param name="msg">输出信息</param>
        public static void WriteMessageToFile(string path, string msg)
        {
            try
            {
                ////读取文件
                //using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                //{
                //    using (StreamReader sr = new StreamReader(fs,Encoding.Default))
                //    {
                //        //sr.ReadToEnd().Remove(0);
                //        //string content = sr.ReadToEnd();//这个就是文本内容
                //        //content = content.Remove(0);//清除内容
                //        Console.WriteLine(sr.ReadToEnd());
                //        sr.Close();
                //    }
                //    Console.ReadKey();
                //}

                //写入文件
                //FileMode.Create如果文件存在就是覆盖文件,FileMode.OpenOrCreate如果文件存在就是追加文件内容
                using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    using (StreamWriter sw = new StreamWriter(fs))
                    {
                        sw.BaseStream.Seek(0, SeekOrigin.End);
                        sw.WriteLine("{0}\r\n", msg, DateTime.Now);
                        sw.Flush();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

 

    public class RetrunEntity
    {
        public decimal payment_back { get; set; }
        public string bank_type { get; set; }
        public string transaction_id { get; set; }
        public string time_end { get; set; }
    }

 

 

posted on 2023-04-05 17:17  Jankie1122  阅读(237)  评论(0编辑  收藏  举报