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. [Evolutionary Algorithm] 进化算法简介

    进化算法,也被成为是演化算法(evolutionary algorithms,简称EAs),它不是一个具体的算法,而是一个“算法簇”.进化算法的产生的灵感借鉴了大自然中生物的进化操作,它一般包括基因编 ...

  2. c++语言友元函数和成员函数对运算符重载

    #include<iostream> using namespace std; /******************************************/ /*use mem ...

  3. Redis-3.2.6 配置文件中文翻译

    ############## # 指定配置文件: ################################## INCLUDES ############################### ...

  4. windows安装rabbitmq

    官网下载windows安装版本:http://www.rabbitmq.com/install-windows.html ,安装文件rabbitmq-server-3.6.5.exe 前提:安装erl ...

  5. 安卓app开发笔记

    移动app应用开发也是信息技术课程科技创新的范畴,所以在个人开发app时候记录一些笔记,可能会很乱,所以选择按点来写. 首先是一些入门的资料,有很多需要自己学习的 https://www.oschin ...

  6. 转载:如何让spring mvc web应用启动时就执行

    转载:如何让spring mvc web应用启动时就执行特定处理 http://www.cnblogs.com/yjmyzz/p/4747251.html# Spring-MVC的应用中 一.Appl ...

  7. BZOJ 2079: [Poi2010]Guilds

    Description 问一个图是否有二染色方案,满足每个点都跟他颜色不用的点有连边. Sol 结论题. 除了只有一个点,否则任何图都能被二染色. Code /******************** ...

  8. python中单引号, 双引号,三引号的差异

    1. 单引号和双引号用法都是一样的,但是如果字符串里有相同的字符时要使用\进行转义 举例:1) print 'hello'2) print "hello"1和2,结果都是hello ...

  9. git: fatal: Not a git repository (or any of the parent directories): .git

    在看书 FlaskWeb开发:基于Python的Web应用开发实战 时,下载完源码后 git clone https://github.com/miguelgrinberg/flasky.git 试着 ...

  10. .net测试学习--理解.net测试选项

    1.创建基于测试简单应用程序 (1)启动visual studio(有安装c#的) (2)  选择File|New project (3)创建一个C# project,名字和保存路径自己设定,假设取名 ...