C#: using JsonReader avoid Deserialize Json to dynamic


namespace Test
{
    using Microshaoft;
    using Test.Models;
    using Newtonsoft.Json;
    using System;
    using System.Web.Script.Serialization;
    class Program
    {
        static void Main(string[] args)
        {
            string json = @"{
                                ""Header"" :
                                        {
                                            ""Topic"" : ""Topic001""
                                            , ""From"" : ""张三""
                                            , ""To"" : [""李四"",""jhjhj""]
                                        }
                                , ""Body"" :
                                        {
                                            ""DisplayName"" : ""杨小军""
                                            , ""PictureUrl"" : null
                                            , ""Title"" : ""总经理""
                                        }
                            }";
            var paths = new string[]
                                {
                                    "Header.Topic"
                                    , "Body"
                                };
            string topic = string.Empty;
            JsonReaderHelper.ReadJsonPathsValuesAsStrings
                                (
                                    json
                                    , paths
                                    , (x, y) =>
                                    {
                                        //if (x == paths[0])
                                        {
                                            topic = y;
                                        }
                                        return true;
                                    }
                                );
            if (topic == "Topic001")
            {
                Topic001Message message = SerializerHelper.DataContractSerializerJsonToObject<Topic001Message>(json);
                Console.WriteLine(message.Header.To[0]);
                Console.WriteLine(message.Body.DisplayName);
                var javaScriptSerializer = new JavaScriptSerializer();
                var jsonObject = javaScriptSerializer.Serialize(message);
                Console.WriteLine(json);
            }
            Console.WriteLine(topic);
            Console.ReadLine();
        }
    }
}
namespace Microshaoft
{
    using Newtonsoft.Json;
    using System;
    using System.IO;
    public static class JsonReaderHelper
    {
        public static void ReadJsonPathsValuesAsStrings
                            (
                                string json
                                , string[] jsonPaths
                                , Func<string, string, bool> onReadedOncePathStringValueProcesssFunc = null
                            )
        {
            using (var stringReader = new StringReader(json))
            {
                using (var jsonReader = new JsonTextReader(stringReader))
                {
                    bool breakAndReturn = false;
                    while
                        (
                            jsonReader.Read()
                            && !breakAndReturn
                        )
                    {
                        foreach (var x in jsonPaths)
                        {
                            if (x == jsonReader.Path)
                            {
                                if (onReadedOncePathStringValueProcesssFunc != null)
                                {
                                    var s = jsonReader.ReadAsString();
                                    breakAndReturn = onReadedOncePathStringValueProcesssFunc
                                            (
                                                x
                                                , s
                                            );
                                    if (breakAndReturn)
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
namespace Test.Models
{
    public class MessageHeader
    {
        public string Topic;
        public string From;
        public string[] To;
    }
    public class Topic001Message
    {
        public MessageHeader Header;
        public Topic001Body Body;
    }
    public class Topic001Body
    {
        public string DisplayName;
        public string PictureUrl;
        public string Title;
    }
}
namespace Microshaoft
{
    using System.IO;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Runtime.Serialization.Formatters.Soap;
    using System.Runtime.Serialization.Json;
    using System.Text;
    using System.Xml;
    using System.Xml.Serialization;
    public static class SerializerHelper
    {
        public static T XmlSerializerXmlToObject<T>(string xml, XmlSerializer serializer = null)
        {
            StringReader stringReader = new StringReader(xml);
            XmlReader xmlReader = XmlReader.Create(stringReader);
            if (serializer == null)
            {
                serializer = new XmlSerializer(typeof(T));
            }
            return (T)serializer.Deserialize(xmlReader);
        }
        public static string XmlSerializerObjectToXml<T>(T target, XmlSerializer serializer = null, XmlWriterSettings settings = null)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                using (XmlWriter writer = XmlTextWriter.Create(stream, settings))
                {
                    if (serializer == null)
                    {
                        serializer = new XmlSerializer(typeof(T));
                    }
                    serializer.Serialize(writer, target);
                    byte[] buffer = StreamDataHelper.ReadDataToBytes(stream);
                    if (settings == null)
                    {
                        settings = writer.Settings;
                    }
                    var e = settings.Encoding;
                    var p = e.GetPreamble().Length;
                    string s = e.GetString(buffer, p, buffer.Length - p);
                    writer.Close();
                    return s;
                }
            }
        }
        public static string DataContractSerializerObjectToXml<T>(T target, DataContractSerializer serializer)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, target);
                byte[] buffer = StreamDataHelper.ReadDataToBytes(ms);
                string xml = Encoding.UTF8.GetString(buffer);
                ms.Close();
                return xml;
            }
        }
        public static string DataContractSerializerObjectToXml<T>(T target)
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(T));
            string xml = DataContractSerializerObjectToXml<T>(target, serializer);
            return xml;
        }
        public static T DataContractSerializerXmlToObject<T>(string xml, DataContractSerializer serializer)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(xml);
            using (MemoryStream ms = new MemoryStream(buffer))
            {
                T target = (T)serializer.ReadObject(ms);
                ms.Close();
                return target;
            }
        }
        public static T DataContractSerializerXmlToObject<T>(string xml)
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(T));
            byte[] buffer = Encoding.UTF8.GetBytes(xml);
            using (MemoryStream ms = new MemoryStream(buffer))
            {
                T target = (T)serializer.ReadObject(ms);
                ms.Close();
                return target;
            }
        }
        public static string FormatterObjectToSoap<T>(T target)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                SoapFormatter formatter = new SoapFormatter();
                formatter.Serialize(stream, target);
                string soap = Encoding.UTF8.GetString(stream.GetBuffer());
                return soap;
            }
        }
        public static T FormatterSoapToObject<T>
                                    (
                                        string soap
                                    )
        {
            using (MemoryStream stream = new MemoryStream())
            {
                SoapFormatter formater = new SoapFormatter();
                byte[] data = Encoding.UTF8.GetBytes(soap);
                stream.Write(data, 0, data.Length);
                stream.Position = 0;
                T target = (T)formater.Deserialize(stream);
                return target;
            }
        }
        public static byte[] FormatterObjectToBinary<T>
                                    (
                                        T target
                                    )
        {
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter formater = new BinaryFormatter();
                formater.Serialize(stream, target);
                byte[] buffer = stream.ToArray();
                return buffer;
            }
        }
        public static T FormatterBinaryToObject<T>
                                    (
                                        byte[] data
                                    )
        {
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter formater = new BinaryFormatter();
                stream.Write(data, 0, data.Length);
                stream.Position = 0;
                T target = (T)formater.Deserialize(stream);
                return target;
            }
        }
        public static string DataContractSerializerObjectToJson<T>(T target)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            string json = DataContractSerializerObjectToJson<T>(target);
            return json;
        }
        public static string DataContractSerializerObjectToJson<T>(T target, DataContractJsonSerializer serializer)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, target);
                string json = Encoding.UTF8.GetString(ms.GetBuffer());
                ms.Close();
                return json;
            }
        }
        public static T DataContractSerializerJsonToObject<T>(string json)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            T target = DataContractSerializerJsonToObject<T>(json, serializer);
            return target;
        }
        public static T DataContractSerializerJsonToObject<T>(string json, DataContractJsonSerializer serializer)
        {
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
            T target = (T)serializer.ReadObject(ms);
            ms.Close();
            ms.Dispose();
            ms = null;
            return target;
        }
    }
}
namespace Microshaoft
{
    using System.IO;
    public static class StreamDataHelper
    {
        public static byte[] ReadDataToBytes(Stream stream)
        {
            byte[] buffer = new byte[64 * 1024];
            MemoryStream ms = new MemoryStream();
            int r = 0;
            int l = 0;
            long position = -1;
            if (stream.CanSeek)
            {
                position = stream.Position;
                stream.Position = 0;
            }
            while (true)
            {
                r = stream.Read(buffer, 0, buffer.Length);
                if (r > 0)
                {
                    l += r;
                    ms.Write(buffer, 0, r);
                }
                else
                {
                    break;
                }
            }
            byte[] bytes = new byte[l];
            ms.Position = 0;
            ms.Read(bytes, 0, (int)l);
            ms.Close();
            ms.Dispose();
            ms = null;
            if (position >= 0)
            {
                stream.Position = position;
            }
            return bytes;
        }
    }
}

C#: using JsonReader avoid Deserialize Json to dynamic,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。