用c#写一个json的万能解析器
CommonJsonModel .cs
/// <summary>
/// 万能JSON解析器
/// </summary>
public class CommonJsonModel : CommonJsonModelAnalyze
{
private string rawjson;
private bool isValue = false;
private bool isModel = false;
private bool isCollection = false;
internal CommonJsonModel(string rawjson)
{
this.rawjson = rawjson;
if (string.IsNullOrEmpty(rawjson))
throw new Exception("missing rawjson");
rawjson = rawjson.Trim();
if (rawjson.StartsWith("{"))
{
isModel = true;
}
else if (rawjson.StartsWith("["))
{
isCollection = true;
}
else
{
isValue = true;
}
}
public string Rawjson
{
get { return rawjson; }
}
public bool IsValue()
{
return isValue;
}
public bool IsValue(string key)
{
if (!isModel)
return false;
if (string.IsNullOrEmpty(key))
return false;
foreach (string subjson in base._GetCollection(this.rawjson))
{
CommonJsonModel model = new CommonJsonModel(subjson);
if (!model.IsValue())
continue;
if (model.Key == key)
{
CommonJsonModel submodel = new CommonJsonModel(model.Value);
return submodel.IsValue();
}
}
return false;
}
public bool IsModel()
{
return isModel;
}
public bool IsModel(string key)
{
if (!isModel)
return false;
if (string.IsNullOrEmpty(key))
return false;
foreach (string subjson in base._GetCollection(this.rawjson))
{
CommonJsonModel model = new CommonJsonModel(subjson);
if (!model.IsValue())
continue;
if (model.Key == key)
{
CommonJsonModel submodel = new CommonJsonModel(model.Value);
return submodel.IsModel();
}
}
return false;
}
public bool IsCollection()
{
return isCollection;
}
public bool IsCollection(string key)
{
if (!isModel)
return false;
if (string.IsNullOrEmpty(key))
return false;
foreach (string subjson in base._GetCollection(this.rawjson))
{
CommonJsonModel model = new CommonJsonModel(subjson);
if (!model.IsValue())
continue;
if (model.Key == key)
{
CommonJsonModel submodel = new CommonJsonModel(model.Value);
return submodel.IsCollection();
}
}
return false;
} /// <summary>
/// 当模型是对象,返回拥有的key
/// </summary>
/// <returns></returns>
public List<string> GetKeys()
{
if (!isModel)
return null;
List<string> list = new List<string>();
foreach (string subjson in base._GetCollection(this.rawjson))
{
string key = new CommonJsonModel(subjson).Key;
if (!string.IsNullOrEmpty(key))
list.Add(key);
}
return list;
}
/// <summary>
/// 当模型是对象,key对应是值,则返回key对应的值
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public string GetValue(string key)
{
if (!isModel)
return null;
if (string.IsNullOrEmpty(key))
return null;
foreach (string subjson in base._GetCollection(this.rawjson))
{
CommonJsonModel model = new CommonJsonModel(subjson);
if (!model.IsValue())
continue;
if (model.Key == key)
return model.Value;
}
return null;
}
/// <summary>
/// 模型是对象,key对应是对象,返回key对应的对象
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public CommonJsonModel GetModel(string key)
{
if (!isModel)
return null;
if (string.IsNullOrEmpty(key))
return null;
foreach (string subjson in base._GetCollection(this.rawjson))
{
CommonJsonModel model = new CommonJsonModel(subjson);
if (!model.IsValue())
continue;
if (model.Key == key)
{
CommonJsonModel submodel = new CommonJsonModel(model.Value);
if (!submodel.IsModel())
return null;
else
return submodel;
}
}
return null;
}
/// <summary>
/// 模型是对象,key对应是集合,返回集合
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public CommonJsonModel GetCollection(string key)
{
if (!isModel)
return null;
if (string.IsNullOrEmpty(key))
return null;
foreach (string subjson in base._GetCollection(this.rawjson))
{
CommonJsonModel model = new CommonJsonModel(subjson);
if (!model.IsValue())
continue;
if (model.Key == key)
{
CommonJsonModel submodel = new CommonJsonModel(model.Value);
if (!submodel.IsCollection())
return null;
else
return submodel;
}
}
return null;
}
/// <summary>
/// 模型是集合,返回自身
/// </summary>
/// <returns></returns>
public List<CommonJsonModel> GetCollection()
{
List<CommonJsonModel> list = new List<CommonJsonModel>();
if (IsValue())
return list;
foreach (string subjson in base._GetCollection(rawjson))
{
list.Add(new CommonJsonModel(subjson));
}
return list;
} /// <summary>
/// 当模型是值对象,返回key
/// </summary>
private string Key
{
get
{
if (IsValue())
return base._GetKey(rawjson);
return null;
}
}
/// <summary>
/// 当模型是值对象,返回value
/// </summary>
private string Value
{
get
{
if (!IsValue())
return null;
return base._GetValue(rawjson);
}
}
}
CommonJsonModelAnalyze.cs
public class CommonJsonModelAnalyze
{
protected string _GetKey(string rawjson)
{
if (string.IsNullOrEmpty(rawjson))
return rawjson;
rawjson = rawjson.Trim();
string[] jsons = rawjson.Split(new char[] { ':' });
if (jsons.Length < )
return rawjson;
return jsons[].Replace("\"", "").Trim();
}
protected string _GetValue(string rawjson)
{
if (string.IsNullOrEmpty(rawjson))
return rawjson;
rawjson = rawjson.Trim();
string[] jsons = rawjson.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
if (jsons.Length < )
return rawjson;
StringBuilder builder = new StringBuilder();
for (int i = ; i < jsons.Length; i++)
{
builder.Append(jsons[i]);
builder.Append(":");
}
if (builder.Length > )
builder.Remove(builder.Length - , );
string value = builder.ToString();
if (value.StartsWith("\""))
value = value.Substring();
if (value.EndsWith("\""))
value = value.Substring(, value.Length - );
return value;
}
protected List<string> _GetCollection(string rawjson)
{
//[{},{}]
List<string> list = new List<string>();
if (string.IsNullOrEmpty(rawjson))
return list;
rawjson = rawjson.Trim();
StringBuilder builder = new StringBuilder();
int nestlevel = -;
int mnestlevel = -;
for (int i = ; i < rawjson.Length; i++)
{
if (i == )
continue;
else if (i == rawjson.Length - )
continue;
char jsonchar = rawjson[i];
if (jsonchar == '{')
{
nestlevel++;
}
if (jsonchar == '}')
{
nestlevel--;
}
if (jsonchar == '[')
{
mnestlevel++;
}
if (jsonchar == ']')
{
mnestlevel--;
}
if (jsonchar == ',' && nestlevel == - && mnestlevel == -)
{
list.Add(builder.ToString());
builder = new StringBuilder();
}
else
{
builder.Append(jsonchar);
}
}
if (builder.Length > )
list.Add(builder.ToString());
return list;
}
}
上面是json的C#的一个解析器,下面是方法的调用
/// <summary>
/// 引用此方法
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public static CommonJsonModel DeSerialize(string json)
{
return new CommonJsonModel(json);
}
上面的方法的引用,下面是引用之后的解析实例
/// <summary>
/// 解析JSON:返回Checking Availability & Pricing
/// </summary>
/// <param name="checkAvailabilityJson"></param>
/// <param name="PickupClass">变量;为空值时返回false</param>
/// <returns>包含Hotel时获取Itineraries列表</returns>
public static List<Decode_PickupClassHotelList> GetListHotels(string checkAvailabilityJson, string PickupClass)
{
List<Decode_PickupClassHotelList> db_ListHotel = new List<Decode_PickupClassHotelList>();
CommonJsonModel model = DeSerialize(checkAvailabilityJson);
//酒店不为空时
if (PickupClass != "false")
{
//是否有就酒店接送的免费服务
string PickupServiceAvailable=model.GetValue("PickupServiceAvailable");
if(PickupServiceAvailable.ToLower().Trim().Equals("true"))
{
//获取Hotel酒店列表
List<CommonJsonModel> ListHotel = model.GetModel("PickupClassHotelList").GetCollection("" + PickupClass + "").GetCollection();
if (ListHotel.Count > )
{
foreach (var p in ListHotel)
{
Decode_PickupClassHotelList db_model = new Decode_PickupClassHotelList();
db_model.id = p.GetValue("id");
db_ListHotel.Add(db_model);
}
}
}
}
return db_ListHotel;
}
用c#写一个json的万能解析器的更多相关文章
- 自己动手写一个编译器Tiny语言解析器实现
然后,上一篇文章简介Tiny词法分析,实现语言.本文将介绍Tiny的语法分析器的实现. 1 Tiny语言的语法 下图是Tiny在BNF中的文法. 文法的定义能够看出.INNY语言有以下特点: 1 程序 ...
- java 写一个JSON解析的工具类
上面是一个标准的json的响应内容截图,第一个红圈”per_page”是一个json对象,我们可以根据”per_page”来找到对应值是3,而第二个红圈“data”是一个JSON数组,而不是对象,不能 ...
- 单片机裸机下写一个自己的shell调试器(转)
源: 单片机裸机下写一个自己的shell调试器
- 一起写一个JSON解析器
[本篇博文会介绍JSON解析的原理与实现,并一步一步写出来一个简单但实用的JSON解析器,项目地址:SimpleJSON.希望通过这篇博文,能让我们以后与JSON打交道时更加得心应手.由于个人水平有限 ...
- 有强迫症的我只能自己写一个json格式化工具
缘由 为什么博客园的markdown解析出问题了啊?好奇怪啊! 一直以来在编码规范界有2大争论不休的话题,一个是关于是用空格缩进还是tab缩进的问题,一个是花括号是否换行的问题,笔者是tab缩进和花括 ...
- 手写一个json格式化 api
最近写的一个东西需要对json字符串进行格式化然后显示在网页上面. 我就想去网上找找有没有这样的api可以直接调用.百度 json api ,搜索结果都是那种只能在网页上进行校验的工具,没有api. ...
- 我为什么要再给lua写一个json模块
最近要给自己编写的服务器加上json解析模块.根据我当前的项目,可以预测服务器中使用json的地方: 通信.由于与客户端通信使用google protocolbuffer,仅在与SDK通信中使用jso ...
- 从零开始写一个Tomcat(叁)--请求解析
挖坑挖了这么长时间也该继续填坑了,上文书讲到从零开始写一个Tomcat(贰)--建立动态服务器,讲了如何让服务器解析请求,分离servlet请求和静态资源请求,读取静态资源文件输出或是通过URLCla ...
- 自己DIY出来一个JSON结构化展示器
说来也巧,这个玩意,一直都想亲手写一个,因为一直用着各种网上提供的工具,觉得这个还是有些用途,毕竟,后面的实现思路和原理不是太复杂,就是对json的遍历,然后给予不同节点类型以不同的展现风格. 我这次 ...
随机推荐
- Android Fragment详解
一.什么是Fragment Android在3.0中引入了fragments的概念,主要目的是用在大屏幕设备上--例如平板电脑上,支持更加动态和灵活的UI设计.平板电脑的屏幕要比手机的大得多,有更多的 ...
- Pre-compile (pre-JIT) your assembly on the fly, or trigger JIT compilation ahead-of-time (转)
Introduction All .NET developers know that one of the best features of the CLR is JIT-compilation: J ...
- YouTube上的版权保护
早在2007年的时候,我曾写过一篇名为“YouTube: The Big Copyright Lie”(YouTube:关于版权的弥天大谎)的文章,表达了我对YouTube又爱又恨的情感纠结: 现在回 ...
- 【JavaScript】XMLHttpRequest Level2使用指南
XMLHttpRequest是一个浏览器接口,使得Javascript可以进行HTTP(S)通信. 最早,微软在IE 5引进了这个接口.因为它太有用,其他浏览器也模仿部署了,ajax操作因此得以诞生. ...
- 【AngularJS】AngularJS 教程
AngularJS通过新的属性和表达式扩展了HTML.------------->扩展HTML属性 AngularJS可以构建一个单页面应用程序(SPAs: Single Page Applic ...
- SQL Server事务日志介绍
SQL Server中的数据库都是由一或多个数据文件以及一或多个事务日志文件组成的. 顾名思意,数据文件主要存储数据库的数据,包括数据库内容结构,数据页,索引页等等.那么事务日志到底是干什么的呢?它主 ...
- oc-28-构造函数
Dog.h #import <Foundation/Foundation.h> @interface Dog : NSObject { NSString *_name; int _age; ...
- 浅析SkipList跳跃表原理及代码实现
本文将总结一种数据结构:跳跃表.前半部分跳跃表性质和操作的介绍直接摘自<让算法的效率跳起来--浅谈“跳跃表”的相关操作及其应用>上海市华东师范大学第二附属中学 魏冉.之后将附上跳跃表的源代 ...
- HTTP/HTTPS自动加密上网方案
方案介绍 涉及到的软件 BIND: 一个流行的域名解析服务器,我们可以设置哪些域名需要走加密线路. Stunnel: 使用TLS对tcp协议进行加密,也就是对tcp建立一条加密线路. SNI Prox ...
- 永远不要在Linux 执行的 10 个最危险的命令
转: http://www.tecmint.com/10-most-dangerous-commands-you-should-never-execute-on-linux/ http://www.l ...