用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的遍历,然后给予不同节点类型以不同的展现风格. 我这次 ...
随机推荐
- NodeJs使用Mysql模块实现事务处理
依赖模块: 1. mysql:https://github.com/felixge/node-mysql npm install mysql --save 2. async:https://githu ...
- cocos2d-x 2.2 资源更新AssetsManager例子代码
转自:http://www.58player.com/blog-2327-601.html // // UpgradeLayer.h // AmazeDemo // // Created by lsw ...
- Thread message loop for a thread with a hidden window? Make AllocateHwnd safe
Thread message loop for a thread with a hidden window? I have a Delphi 6 application that has a thre ...
- python学习进阶一
map()函数 def format_name(s): return s.capitalize() print map(format_name, ['adam', 'LISA', 'barT']) R ...
- Java练习之最大相同子串
package string.demo; /* 需求:找到两个字符串的最长共同子串 * 思路: * 1.先看短的那个字符串是否在长的那个字符串中,如果存在,短的那个字符串就是最大共同子串 * 2.如果 ...
- IOS 7 Study - UIDatePicker
Picking the Date and Time with UIDatePicker effect: 1. declaring a property of type UIDatePicker #im ...
- Codeforces Round #337 (Div. 2) A. Pasha and Stick 数学
A. Pasha and Stick 题目连接: http://www.codeforces.com/contest/610/problem/A Description Pasha has a woo ...
- 目标检測的图像特征提取之(一)HOG特征
1.HOG特征: 方向梯度直方图(Histogram of Oriented Gradient, HOG)特征是一种在计算机视觉和图像处理中用来进行物体检測的特征描写叙述子.它通过计算和统计图像局部区 ...
- android环境部署(1.1)
前言 对于android文件的解释和说明下载,这里分享一个博客大家了解吧.这里作者提供的下载地址可能有无效的,关键是解析..... 转自:http://www.cnblogs.com/bjzhangh ...
- alue of type java.lang.String cannot be converted to JSONObject
/** * 4.0以下系统处理掉返回json的BOM头 * * @param jsonStr * @return */ public static String getJson(String json ...