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. Windows下安装Oracle拖慢开机速度的解决方法

    环境:win7 + oracle R2 方法:将安装Oracle后自动开机启动的服务改为手动启动 步骤如下: 1.修改服务项 Ctrl + R,输入services.msc,打开服务列表,找到Orac ...

  2. Apache Shiro 学习记录5

    本来这篇文章是想写从Factory加载ini配置到生成securityManager的过程的....但是貌似涉及的东西有点多...我学的又比较慢...很多类都来不及研究,我又怕等我后面的研究了前面的都 ...

  3. JavaScript 智能社 拖拽

    <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title> ...

  4. DNA解链统计物理

    来源:Kerson Huang, Lectures on Statistical Physics and Protein Folding, pp 24-25 把双链DNA解开就像拉拉链.设DNA有\( ...

  5. SQL语句生成指定范围内随机数

    1.生成随机实型数据 create procedure awf_RandDouble @min dec(14,2), @max dec(14,2), @result dec(14,2) output ...

  6. java程序员快速掌握python系列——概述

    这一系列主要是总结学习python过程中的方方面面(已经学完,时间大概是一周左右).当然限于个人水平java也就是够用,python短时间内也不可能深入到哪里去.所以这次的分享的目的是能够快速使用py ...

  7. android 弹出AlertDialog的学习案例

    我在编写的时候,测试的关键代码: AlertDialog.Builder builder=new AlertDialog.Builder(MainPointListActivity.this); bu ...

  8. 为什么axios请求接口会发起两次请求

    之前在使用axios发现每次调用接口都会有两个请求,第一个请求时option请求,而且看不到请求参数,当时也没注意,只当做是做了一次预请求,判断接口是否通畅,但是最近发现并不是那么回事. 首先我们知道 ...

  9. Sql Server创建函数

    在使用数据库的过程中,往往我们需要对有的数据先进行计算,然后再查询出来,所以我们就需要创建函数来完成这项任务,在数据库的Programmability(如图1)下面的Function中创建函数(如图2 ...

  10. winform 跨线程操作控件

    当进行winform的开发时,经常遇到用时比较久的操作,在传统的单线程程序中,用户必须等待这个耗时操作完成以后才能进行下一步的操作,这个时候,多线程编程就派上用场了,将这个耗时的操作放到一个新的子线程 ...