namespace Test
{
using Microshaoft;
using Test.Models;
using Newtonsoft.Json;
using System;
using System.Web.Script.Serialization;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Environment.Version.ToString());
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")
{
var javaScriptSerializer = new JavaScriptSerializer();
//Topic001Message message = SerializerHelper.DataContractSerializerJsonToObject<Topic001Message>(json);
Topic001Message message = javaScriptSerializer.Deserialize<Topic001Message>(json);
Console.WriteLine(message.Header.To[0]);
Console.WriteLine(message.Body.DisplayName);
//转义测试
message.Body.DisplayName = json;
//json = SerializerHelper.DataContractSerializerObjectToJson<Topic001Message>(message);
//Console.WriteLine("DataContractSerializerObjectToJson:{0}{1}", "\n\t", json);
json = javaScriptSerializer.Serialize(message);
Console.WriteLine("javaScriptSerializer.Serialize:{0}{1}", "\n\t", json);
message = javaScriptSerializer.Deserialize<Topic001Message>(json);
Console.WriteLine("DisplayName:: {0}", message.Body.DisplayName);
}
Console.WriteLine(topic);
Console.WriteLine("Hello World");
Console.WriteLine(Environment.Version.ToString());
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的更多相关文章

  1. [Cannot deserialize JSON array into type] NewtonSoft.Json解析数据出错原因

    今天用NewtonSoft.JSon解析一个天气数据,数据格式如: {"status":1,"detail":"\u6570\u636e\u83b7\ ...

  2. C# json to dynamic object

    dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject(json); string greeting = obj.greeting; R ...

  3. android用jsonReader来解析json

    对于这个json: { "id" : "3232", "data" : [{ "data1" : "555&q ...

  4. Json 转 dynamic

    直接上代码: var model = JsonConvert.DeserializeObject<dynamic>("{\"ResponseResult\": ...

  5. Browser Link: Failed to deserialize JSON in Browser Link call

    问题 VS2013中调试程序发现,在浏览器控制台输出如下截图代码:

  6. 【.NET】Browser Link: Failed to deserialize JSON in Browser Link call

    问题 VS2013中调试程序发现,在浏览器控制台输出如下截图代码:

  7. dynamic获取类型可变的json对象

    使用dynamic获取类型可变的json对象 Dictionary<string, object> dict = new Dictionary<string, object>( ...

  8. 使用 dynamic 标记解析JSON字符串 JDynamic :支持Json反序列化为Dynamic对象

    使用 dynamic 标记解析JSON字符串  http://www.cnblogs.com/taotaodetuer/p/4171327.html 1 string jsonStr = " ...

  9. Android 之 json数据的解析(jsonReader)

    json数据的解析相对而言,还是比较容易的,实现的代码也十分简单.这里用的是jsonReade方法来进行json数据解析. 1.在解析之前,大家需要知道什么是json数据. json数据存储的对象是无 ...

随机推荐

  1. Spring MVC学习笔记——文件上传

    1.实现文件上传首先需要导入Apache的包,commons-fileupload-1.2.2.jar和commons-io-2.1.jar 实现上传就在add.jsp文件中修改表单 enctype= ...

  2. log4net位置与使用方法

    <log4net> <appender name="RollingLogFileAppender" type="log4net.Appender.Rol ...

  3. Python PIP安装

    https://zhidao.baidu.com/question/550936793.html 按图做

  4. 截取UTF-8编码的汉字,最后一个字出现乱码的问题

    问题描述 原来字串内容name为下面内容: ######name=杨乃文做DJ,微信公众号FunRadio.什么样的姿态是小丑姿态?2016046###### 需要截取成大小为64的name_rm[6 ...

  5. 提升mysql性能的建议

    使用show status命令查看mysql状态相关的值及其含义:使用show status命令含义如下:aborted_clients 客户端非法中断连接次数aborted_connects 连接m ...

  6. JS这些代码你都不会,你还有什么好说的!!!

    都说自己工资低的,先看看这些代码你能写出来不?这些都不会,你还嫌工资?

  7. 关于li元素嵌套的事儿

    今天阅读<锋利的jQuery>第二版2.6节案例研究部分的时候,遇到一个问题. <ul> <li class="a1"><a href=& ...

  8. JavaWeb基础学习体系与学习思路

    对于JAVAWEB的学习,首先一定要明确的是学习整体框架和思路,要有一个把控.对于WEB,很多人认为是做网页,简单的把静态网页与JAVAWEB与网页设计一概而论. 拿起一本JS就开始无脑的学习,学了一 ...

  9. N皇后问题—初级回溯

    N皇后问题,最基础的回溯问题之一,题意简单N*N的正方形格子上放置N个皇后,任意两个皇后不能出现在同一条直线或者斜线上,求不同N对应的解. 提要:N>13时,数量庞大,初级回溯只能保证在N< ...

  10. getPx function

    function getPX(str){  return str.substring(0,str.indexOf('px'));}