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. mysql复习相关

    Mysql相关 mysql增删改查 我们需要修改数据表名或者修改数据表字段时,就需要使用到Mysql Alter命令 删除,添加或修改表字段 alter table student drop regi ...

  2. sublime 安装插件GitGutter报错,git binary cannot be found等等

    今天给sublime text安装插件GitGutter的时候,居然报错了,网上查找了下解决方法,在此记录下.因为本博主的电脑是windows的,所以这里只能提供windows的方法啦. 解决方法很简 ...

  3. 数据存储_FMDB

    一.简单说明 1.什么是FMDB FMDB是iOS平台的SQLite数据库框架 FMDB以OC的方式封装了SQLite的C语言API 2.FMDB的优点 使用起来更加面向对象,省去了很多麻烦.冗余的C ...

  4. ThinkPHP 隐藏URL中的 index.php

    去掉 URL 中的 index.php 通常的URL里面含有index.php,为了达到更好的SEO效果可能需要去掉URL里面的index.php ,通过URL重写的方式可以达到这种效果,通常需要服务 ...

  5. .htaccess语法之RewriteCond与RewriteRule指令格式详细解释

    htaccess语法之RewriteCond与RewriteRule指令格式详细解释 (2012-11-09 18:09:08) 转载▼ 标签:  htaccess it 分类: 网络 上文htacc ...

  6. 记一次Suse下的Django环境配置——第一弹

    一.安装Python 由于原有Suse自带的Python版本只有2.4,因此首先需要安装Python的高版本,在这里我选择使用Python2.7.9.PS:之前选择使用2.7.11版本,由于没有zli ...

  7. 【codevs1282】约瑟夫问题

    题目描述 有编号从1到N的N个小朋友在玩一种出圈的游戏.开始时N个小朋友围成一圈,编号为I+1的小朋友站在编号为I小朋友左边.编号为1的小朋友站在编号为N的小朋友左边.首先编号为1的小朋友开始报数,接 ...

  8. js中typeof和instanceof

    对于typeof和instanceof,我们经常用来检测数据的类型.typeof可以检测Number.Boolean.String.Undefined类型,对于其他类型的数据都返回为object:而i ...

  9. postgresql中的CUBE函数

    数据函数简介添加汇总额外信息 数据 --复杂统计函数 CREATE TABLE t3 (color_type varchar(20), in_date varchar(30),color_count ...

  10. Java学习——连接数据库

    1.去官网下载对应版本的Ojdbc.jar(oracle).sqljdbc.jar(sqlserver). 2.放置到项目lib文件夹下 3.项目右键->Build Path->confi ...