这是一篇关于在后台使用C#语言将Json字符串转化为对象集合类的介绍,适用于处理后台接收Json字符串,将Json字符串转Xml或者其他格式的场合。
主要的思想如下:
JsonProxy类
json集合使用List<List<JsonClass>>表示。
json对象使用List<JsonClass>表示。
其中JsonClass表示Json字符串一个一个的Key-Value。
==》JsonClass(key,value,type,fullstring......)
//Create By YZR
public class JsonClass { #region 成员 //===>"name":"YZR" private string fullString; public string FullString { get { return fullString; } set { fullString = value; } } private string key; public string Key { get { return key; } set { key = value; } } private JsonClass[] jcs; private List<object> valueContainer;//json集合形式,存放的可能是json对象,也可能是object类型值 public List<object> ValueContainer { get { return valueContainer; } set { valueContainer = value; } } private List<List<JsonClass>> jsonContainer; public List<List<JsonClass>> JsonContainer { get { return jsonContainer; } set { jsonContainer = value; } } public JsonClass[] Jcs { get { return jcs; } set { jcs = value; } } private object value; public object Value { get { return this.value; } set { this.value = value; } } private SubJsonType valueType; public SubJsonType ValueType { get { return valueType; } set { valueType = value; } } #endregion #region 构造函数 public JsonClass() { } public JsonClass(string key, object value) { this.key = key; this.value = value; this.fullString = key + ":" + value; } public JsonClass(string key, List<object> valueContainer) { this.key = key; this.valueContainer = valueContainer; }//集合 public JsonClass(string key, JsonClass[] jcs) { this.key = key; this.jcs = jcs; }//对象 public JsonClass(string str) { this.fullString = str; init(); } #endregion private void init() { JosnProxy jp = new JosnProxy(fullString); jp.init(); if (jp.JsonType == JsonType.Object)//json对象 { List<JsonClass> list = jp.JsonList; JsonClass temp = new JsonClass(); JsonClass[] jsc = new JsonClass[list.Count]; for (int i = 0; i < list.Count; i++) { jsc[i] = list[i]; } this.Jcs = jsc; } else if (jp.JsonType == JsonType.List)//json集合 { SubJsonType subType = JsonParse.JudgeJsonType(fullString.Substring(1, fullString.Length - 2)); //SubJsonType subType = JsonParse.JudgeJsonType(fullString); switch (subType) { case SubJsonType.Object: this.valueContainer = jp.valueContainer; break; case SubJsonType.JsonClass: this.jsonContainer = jp.jsonContainer; break; } } } }
将json转为对象主要是通过JsonProxy类进行的。
/// <summary> /// json代理类 Create By YZR /// </summary> public class JosnProxy { //json字符流 private char[] jsonArray; //json字符串 private string jsonString; public string JsonString { get { return jsonString; } set { jsonString = value; } } //json字符串长度 private int jsonLength; public int JsonLength { get { return jsonLength; } set { jsonLength = value; } } public JosnProxy(string _jsonString) { this.jsonString = _jsonString; toArray(); jsonList = new List<JsonClass>(); jsonLength = jsonString.Length; } /// <summary> /// 得到json字符流 /// </summary> /// <returns></returns> public char[] toArray() { jsonArray = jsonString.ToCharArray(); return jsonArray; } /// <summary> /// json对象 /// </summary> private List<JsonClass> jsonList; public List<JsonClass> JsonList { get { return jsonList; } set { jsonList = value; } } /// <summary> /// 初始化 /// </summary> public void init() { switch (JsonParse.ToJsonCode(jsonArray[0])) { case JsonKey.LeftBraces: Begin(JsonType.Object); break; case JsonKey.LeftMiddle: Begin(JsonType.List); break; case JsonKey.Colon: case JsonKey.Comma: case JsonKey.RightBraces: case JsonKey.RightMiddle: break;//不正常的json字符串 default: break;//包含其他字符串的不正常字符串 } } public void init(JsonKey JK)//JsonParse.ToJsonCode(jsonArray[0]) { switch (JK) { case JsonKey.LeftBraces: Begin(JsonType.Object); break; case JsonKey.LeftMiddle: Begin(JsonType.Object); break; case JsonKey.Colon: case JsonKey.Comma: case JsonKey.RightBraces: case JsonKey.RightMiddle: break;//不正常的json字符串 default: break;//包含其他字符串的不正常字符串 } } private void Begin(JsonType _jsonType) { this.JsonType = _jsonType; JsonObject jObject = new JsonObject(); int i = 1; string jsonClassKey = string.Empty; string jsonClassValue = string.Empty; if (_jsonType == JsonType.List) { #region 处理集合 List<string> list = getJsonObject(jsonString); foreach (string item in list) { SubJsonType subType = JsonParse.JudgeJsonType(item);//对象 if (subType == SubJsonType.JsonClass) { JosnProxy jp = new JosnProxy(item); jp.init(); List<JsonClass> lc = jp.JsonList; jObject.jsonContainer.Add(lc); } else if (subType == SubJsonType.Object)//值 { jObject.valueContainer.Add(item); } } #endregion jsonContainer = jObject.jsonContainer;//对象集合 valueContainer = jObject.valueContainer;//值集合 } else { #region 处理对象 DealJsonList(i, ref jObject, jsonClassKey, jsonClassValue); #endregion jsonList = jObject.jsonClassList;//对象 //jsonContainer = jObject.jsonContainer;//对象集合 //valueContainer = jObject.valueContainer;//值集合 } } private void DealJsonList(int i, ref JsonObject jObject, string jsonClassKey, string jsonClassValue) { while (i > 0 && i < jsonLength)//处理对象 { if (jsonArray[i] == '"') { int EndIndex = FingRightBraces(i); //从开始索引为i到结束索引为EndIndex截取字符串,封装为JsonClass对象,保存在JsonObject对象的 if (string.IsNullOrEmpty(jsonClassKey)) { jsonClassKey = jsonString.Substring(i, EndIndex - i + 1); } else { jsonClassValue = jsonString.Substring(i, EndIndex - i + 1); JsonClass jc = new JsonClass(jsonClassKey, jsonClassValue); jObject.jsonClassList.Add(jc); jsonClassKey = string.Empty; } i = EndIndex + 1; } else if (jsonArray[i] == ',') { i++; } else if (jsonArray[i] == '}') { i = 0; } else if (jsonArray[i] == ':') { i++; } else if (jsonArray[i] == '{')//对象 { int _right = jsonString.IndexOf('}', i); int _left = jsonString.IndexOf('{', i);//嵌套 if (_right != -1) { jsonClassValue = jsonString.Substring(i, _right - i + 1); } JsonClass subJsonClass = new JsonClass(jsonClassValue); JsonClass jc = new JsonClass(jsonClassKey, subJsonClass.Jcs); jc.ValueType = SubJsonType.JsonClass; jObject.jsonClassList.Add(jc); jsonClassKey = string.Empty; i = _right + 1; } else if (jsonArray[i] == '[') { int _right = jsonString.IndexOf(']', i); int _left = jsonString.IndexOf('[', i + 1); SubJsonType subType = SubJsonType.None; if (_left != -1 && _left < _right)//嵌套 { //int Nesting = FindNestingCount(jsonString, i, _right, '[');//嵌套数 // _right = FindRight(jsonString, _right, ']', Nesting); _right = SeniorFindIndex(jsonString, i, '[', ']'); jsonClassValue = jsonString.Substring(i, _right - i + 1); subType = JsonParse.JudgeJsonType(jsonClassValue.Substring(1, jsonClassValue.Length - 2)); } else { jsonClassValue = jsonString.Substring(i, _right - i + 1); subType = JsonParse.JudgeJsonType(jsonClassValue.Substring(1, jsonClassValue.Length - 2)); } JsonClass subJsonClass = new JsonClass(jsonClassValue); //JsonClass[] jsc = new JsonClass[subJsonClass.Jcs.Length]; //jsc[0] = subJsonClass; JsonClass jc; if (subType == SubJsonType.Object) { //jObject.valueContainer = subJsonClass.ValueContainer; jc = new JsonClass(jsonClassKey, subJsonClass.ValueContainer); jc.ValueType = SubJsonType.JslnContainer;//json集合(值集合) jc.FullString = jsonClassKey + ":" + jsonClassValue;//构造函数没赋值fullString,所以需要在这里补上 jObject.jsonClassList.Add(jc); } else if (subType == SubJsonType.JsonClass) { jc = new JsonClass(); jc.Key = jsonClassKey; jc.JsonContainer = subJsonClass.JsonContainer; jc.ValueType = SubJsonType.JslnContainer; jc.FullString = jsonClassKey + ":" + jsonClassValue; jObject.jsonClassList.Add(jc); } else { jc = new JsonClass(); } jsonClassKey = string.Empty; i = _right + 1; } else if (jsonArray[i] == ']') { } else//数值或者布尔值 { int index = jsonString.IndexOf(',', i); if (index == -1) { index = jsonString.IndexOf('}', i); } jsonClassValue = jsonString.Substring(i, index - i); JsonClass jc = new JsonClass(jsonClassKey, jsonClassValue); jc.ValueType = SubJsonType.Object; jObject.jsonClassList.Add(jc); jsonClassKey = string.Empty; i++; } } } private int FingRightBraces(int StartIndex) { return jsonString.IndexOf('"', StartIndex + 1); } /// <summary> /// json集合(对象集合) /// </summary> public List<List<JsonClass>> jsonContainer; /// <summary> /// json集合(值集合) /// </summary> public List<object> valueContainer; private JsonType jsonType; public JsonType JsonType { get { return jsonType; } set { jsonType = value; } } public SubJsonType getType(string _str) { char[] arr = _str.ToCharArray(); switch (JsonParse.ToJsonCode(arr[0])) { case JsonKey.LeftBraces: return SubJsonType.JsonClass; case JsonKey.LeftMiddle: return SubJsonType.JslnContainer; case JsonKey.Quote: case JsonKey.None: return SubJsonType.Object; default: return SubJsonType.None; } } /// <summary> /// 以单个的json对象字符串加入List中 /// </summary> /// <param name="jsonContainer"></param> /// <returns></returns> public List<string> getJsonObject(string jsonContainer) { jsonContainer = jsonContainer.Trim(); char[] arr = jsonContainer.ToCharArray(); if (arr[0] != '[') { return null; } int i = 1; List<string> list = new List<string>(); bool StartContact = false; int BeginTemp = 0; while (i > 0 && i < arr.Length) { if (arr[i] == '{') { int _right = jsonContainer.IndexOf('}', i); int _left = jsonContainer.IndexOf('{', i + 1); if (_left != -1 && _left < _right)//嵌套 { //int Nesting = FindNestingCount(jsonContainer, i, _right, '{');//嵌套数 //_right = FindRight(jsonContainer, _right, '}', Nesting); _right = SeniorFindIndex(jsonContainer, i, '{', '}'); } list.Add(jsonContainer.Substring(i, _right - i + 1)); i = _right + 1; } else if (arr[i] == ',') { if (StartContact) { list.Add(jsonContainer.Substring(BeginTemp, i - BeginTemp)); StartContact = false; } i++; } else if (arr[i] == ']') { //结束 if (StartContact) { list.Add(jsonContainer.Substring(BeginTemp, i - BeginTemp)); StartContact = false; } i++; } else if (arr[i] == '"')//Object之字符串类型 Object之数值字符串或者布尔类型字符串 { if (!StartContact) { StartContact = true; BeginTemp = i; } else { list.Add(jsonContainer.Substring(BeginTemp + 1, i - BeginTemp - 1)); StartContact = false; } i++; } else { //list.Add(arr[i].ToString()); if (!StartContact) { StartContact = true; BeginTemp = i; } //else //{ // list.Add(jsonContainer.Substring(BeginTemp + 1, i - BeginTemp - 1)); // StartContact = false; //} i++; } } return list; } public int SeniorFindIndex(string jsonString, int BeginIndex, char left_word, char right_word) { string subStr = string.Empty; subStr = jsonString.Substring(BeginIndex + 1, jsonString.Length - BeginIndex - 1); List<int> LeftList = new List<int>(); List<int> RightList = new List<int>(); int _left = 0; int _rigth = 0; while (_left != -1 && _rigth != -1) { _left = subStr.IndexOf(left_word, _left); if (_left != -1) { LeftList.Add(_left); _left++; } _rigth = subStr.IndexOf(right_word, _rigth); if (_rigth != -1) { RightList.Add(_rigth); _rigth++; } } int k = 0; bool run = true; while (RightList[k] > LeftList[k] && run) { if (LeftList.Count == k + 1) { run = false; } else { k++; } } return run == true ? RightList[k] + BeginIndex + 1 : RightList[k + 1] + BeginIndex + 1; } /// <summary> /// 单层嵌套 /// </summary> /// <param name="jsonString"></param> /// <param name="BeginIndex"></param> /// <param name="left_word"></param> /// <param name="right_word"></param> /// <returns></returns> public int FindIndex(string jsonString, int BeginIndex, char left_word, char right_word) { //[ [] [] .....( ] 找到这里的索引) string subStr = string.Empty; subStr = jsonString.Substring(BeginIndex + 1, jsonString.Length - BeginIndex - 1); char[] arr = jsonString.ToCharArray(); int _left = 0; int _rigth = 0; while (_left != -1) { _left = subStr.IndexOf(left_word, _left); if (_left != -1) { _left++; } _rigth = subStr.IndexOf(right_word, _rigth); _rigth++; } char temp = arr[_rigth + BeginIndex]; return _rigth + BeginIndex; } public int FindNestingCount(string jsonString, int BeginIndex, int LastIndex, char word) { string subStr = jsonString.Substring(BeginIndex + 1, LastIndex - BeginIndex + 1); int Appear = GetStrCount(subStr, word);//出现次数 return Appear; } public int FindRight(string jsonString, int BeginIndex, char Word, int Pass) { int count = 0; int StartIndex = BeginIndex; while (count <= Pass) { StartIndex = jsonString.IndexOf(Word, StartIndex); StartIndex++; count++; } return StartIndex - 1; } /// <summary> /// 获得字符在字符串中出现的次数 /// </summary> /// <param name="list"></param> /// <param name="str"></param> /// <returns></returns> public int GetStrCount(string str, char Word) { int count = 0; char[] arr = str.ToCharArray(); for (int i = 0; i < arr.Length; i++) { if (arr[i] == Word) { count++; } } return count; } }
注意:这里并没有加上异常处理,所以使用之前需要先确认json是否是一个符合规范并且正确格式的json字符串。
RJson的几个辅助类:
internal class JsonObject { public List<JsonClass> jsonClassList = new List<JsonClass>();//对象 public List<List<JsonClass>> jsonContainer = new List<List<JsonClass>>();//对象集合 public List<object> valueContainer = new List<object>();//值集合 } public enum SubJsonType { Object,//值 JsonClass,//对象 JslnContainer,//集合 None } public enum JsonType { Object,//对象 List,//集合 None } public enum JsonKey { LeftMiddle,//左中括号 [ RightMiddle,//右中括号 ] LeftBraces,//左大括号 { RightBraces,//右大括号 } Comma,//逗号 Colon,//冒号 Quote,//双引号 None } public class JsonParse { /// <summary> /// 判断子对象的json对象 /// </summary> /// <param name="SubString"></param> /// <returns></returns> public static SubJsonType JudgeJsonType(string SubString) { char[] arr = SubString.ToCharArray(); if (SubString.IndexOf('{') == -1 && SubString.IndexOf('[') == -1) { return SubJsonType.Object;//数值 } else if (arr[0] == '[') { return SubJsonType.JslnContainer; } else if (arr[0] == '{') { return SubJsonType.JsonClass; } else return SubJsonType.None; } /// <summary> /// JsonCode=>String /// </summary> /// <param name="JsonCode"></param> /// <returns></returns> public static string ToJsonString(JsonKey JsonCode) { if (JsonCode == null) { return ""; } switch (JsonCode) { case JsonKey.LeftMiddle: return "["; case JsonKey.RightMiddle: return "]"; case JsonKey.LeftBraces: return "{"; case JsonKey.RightBraces: return "}"; case JsonKey.Comma: return ","; case JsonKey.Colon: return ":"; default: return ""; } } /// <summary> /// String=>JsonKey /// </summary> /// <param name="jsonString"></param> /// <returns></returns> public static JsonKey ToJsonCode(string jsonString) { if (string.IsNullOrEmpty(jsonString)) { return JsonKey.None; } switch (jsonString) { case "[": return JsonKey.LeftMiddle; case "]": return JsonKey.RightMiddle; case "{": return JsonKey.LeftBraces; case "}": return JsonKey.RightBraces; case ",": return JsonKey.Comma; case ":": return JsonKey.Colon; case "\"": return JsonKey.Quote; default: return JsonKey.None; } } /// <summary> /// char=>JsonKey /// </summary> /// <param name="jsonString"></param> /// <returns></returns> public static JsonKey ToJsonCode(char jsonString) { if (jsonString == null) { return JsonKey.None; } switch (jsonString) { case '[': return JsonKey.LeftMiddle; case ']': return JsonKey.RightMiddle; case '{': return JsonKey.LeftBraces; case '}': return JsonKey.RightBraces; case ',': return JsonKey.Comma; case ':': return JsonKey.Colon; case '"': return JsonKey.Quote; default: return JsonKey.None; } } }
最后展示一下Demo:
RJson 1.0版本问题: 1.josn字符串本身包含七个关键词需要处理 2.json字符串的异常处理 3.json字符串的验证 //测试代码如下: static void Main(string[] args) { //JsonHelper.JosnString = "{\"number\":2,\"who\":\"YZR\",\"GrilFirend\":{\"Name\":\"LYF\",\"number\":3},\"Firend\":{\"Name\":\"Dog\",\"number\":4,\"Age\":1}}"; //JsonHelper.JosnString = "[{\"Name\":\"YZR\",\"number\":1,\"Firend\":{\"Name\":\"Dog\",\"number\":4,\"Age\":1}},{\"Name\":\"LYF\",\"number\":2,\"Firend\":{\"Name\":\"Dog\",\"number\":4,\"Age\":1,\"Type\":{\"Sex\":\"Man\",\"City\":\"GZ\"}}},{\"Name\":\"Dog\",\"number\":3}]"; //JsonHelper.JosnString = "{\"number\":2,\"who\":[\"YZR\",\"LYF\"],\"Firend\":[{\"Name\":\"Dog\",\"number\":4,\"Age\":1},{\"Name\":\"Dog\",\"number\":4,\"Age\":1}]}"; //JsonHelper.JosnString = "{\"number\":2,\"Firend\":[{\"Name\":\"YZR\",\"Color\":[\"1\",\"2\"]},{\"Name\":\"LYF\",\"Color\":[\"3\",\"4\"]}]}"; JsonHelper.JosnString = "{\"number\":2,\"Firend\":[{\"Name\":\"YZR\",\"Color\":[1,2]},{\"Name\":\"LYF\",\"Color\":[3,4]}]}"; //JsonHelper.JosnString = "[{\"number\":2,\"Firend\":[{\"Name\":\"YZR\",\"Color\":[1,2]},{\"Name\":\"LYF\",\"Color\":[3,4]}]},{\"number\":1}]"; //JsonHelper.JosnString = "[{\"number\":2,\"Firend\":[{\"Name\":\"YZR\",\"Color\":[1,2]},{\"Name\":\"LYF\",\"Color\":[3,4]},{\"number\":1}]}]"; int len = JsonHelper.JosnString.Length; Console.WriteLine("整个长度为:" + len + ",第二个字符是:" + JsonHelper.JosnString[1]); JosnProxy jp = new JosnProxy(JsonHelper.JosnString); jp.init(); if (jp.JsonType == JsonType.Object)//json对象 { List<JsonClass> jsonClasslist = jp.JsonList; #region 业务处理 foreach (JsonClass item in jsonClasslist) { switch (item.ValueType) { case SubJsonType.Object: DealObject(); break; case SubJsonType.JsonClass: DealJsonClass(item); break; default: break; } } #endregion } else//json集合(对象集合) { List<List<JsonClass>> list = jp.jsonContainer;//json集合 #region 业务处理 #endregion } } static void DealObject() { //Do Some Tings } static void DealJsonClass(JsonClass jc) { //Do Some Tings string jsonString = jc.FullString; }