Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1003357
  • 博文数量: 150
  • 博客积分: 3017
  • 博客等级: 少校
  • 技术积分: 3829
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-19 14:40
个人简介

Now in Baidu WISE team

文章分类

全部博文(150)

文章存档

2014年(8)

2013年(31)

2012年(111)

分类: C#/.net

2013-11-19 11:46:06

工作的时候写的一个JSON parser,因为.net的 System.JSON.dll死活import 不进来,就自己写了个。. 虽然很烂,但是不能随便用,有知识产权的呦O(∩_∩)O。仅供参考。

测试代码:

点击(此处)折叠或打开

  1. [TestMethod()]
  2.         public void ParserTest()
  3.         {
  4.             Console.WriteLine("xxxxxxxxxxxxxxxxxxxxxxxxxxxx");
  5.             string content = string.Empty; // TODO: Initialize to an appropriate value
  6.   

  7.             String file = "C:\\Users\\Administrator\\Desktop\\TestData\\test.txt";
  8.             StreamReader sr = new StreamReader(file);
  9.             content = sr.ReadToEnd();
  10.             JSONElement actual = new JSONElement(JsonUtils.Parser(content));
  11.             //actual.withBracket = true;
  12.             Console.WriteLine("xxxxxxxxxxxxxxxxxxxxxxxxxxxx");
  13.             Console.WriteLine(actual.ToString());
  14.            
  15.             //Assert.Inconclusive("Verify the correctness of this test method.");
  16.         }



JSONElement.cs

点击(此处)折叠或打开

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;

  5. namespace JSONMgr
  6. {
  7.     class JSONElement : ICloneable
  8.     {
  9.         public String Key;
  10.         public JsonValueItem Value;
  11.         public bool isAnoy = false;
  12.         public JSONElement(JsonValueItem value)
  13.         {
  14.             this.Key = Guid.NewGuid().ToString();
  15.             this.Value = value;
  16.             this.isAnoy = true;
  17.         }


  18.         public JSONElement()
  19.         {
  20.         }
  21.         public JSONElement(String key, JsonValueItem value)
  22.         {
  23.             this.Key = key;
  24.             this.Value = value;
  25.          
  26.         }
  27.         public JSONElement(String key, List<JSONElement> itemarray)
  28.         {
  29.             this.Key = key;
  30.             this.Value = new JsonValueItem(itemarray);
  31.         }
  32.         private void AddPreTab(StringBuilder sb, int tabcount){
  33.             for(int i = 0; i<tabcount; i++)
  34.                 sb.Append(" ");
  35.         }

  36.         public String GetDisplayString()
  37.         {
  38.             String ret = "";
  39.             if (this.isAnoy)
  40.                 return "JSON";
  41.             if (this.Value.StrValue != null)
  42.             {
  43.                 ret += this.Key;
  44.                 ret += ": ";
  45.                 ret += this.Value.ToString();
  46.                 return ret;
  47.             }
  48.             return this.Key;
  49.             

  50.         }

  51.         private String ToString(int tabcount)
  52.         {
  53.             return "";
  54.         }


  55.         public override String ToString()
  56.         {
  57.             if (this.Value == null)
  58.                 return null;
  59.             StringBuilder sb = new StringBuilder();
  60.             if( !this.isAnoy)
  61.             return this.Key + ": " + this.Value.ToString();
  62.             return this.Value.ToString();
  63.         }

  64.         public object Clone()
  65.         {
  66.             JSONElement ret = new JSONElement();
  67.             String key = Guid.NewGuid().ToString();
  68.             if (!this.isAnoy)
  69.             {
  70.                 key = this.Key;
  71.             }
  72.             else
  73.             {
  74.                 ret.isAnoy = true;
  75.             }
  76.   
  77.             ret.Key = key;
  78.             ret.Value = (JsonValueItem) this.Value.Clone();
  79.  
  80.             return ret;
  81.            
  82.         }

  83.         public JsonValueItem Get(String key)
  84.         {
  85.             if (this.Value.JsonArray != null)
  86.             {
  87.                 foreach (JSONElement je in this.Value.JsonArray)
  88.                 {
  89.                     if (!je.isAnoy && je.Key == key)
  90.                         return je.Value;
  91.                 }
  92.             }
  93.             return null;
  94.         }
  95.     }
  96. }
JsonValueItem

点击(此处)折叠或打开

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;

  5. namespace JSONMgr
  6. {
  7.     public enum ItemType
  8.     {
  9.         Simple, Dict, Array
  10.     }
  11.     class JsonValueItem : ICloneable
  12.     {
  13.         public String StrValue = null;
  14.         public JSONElement JsonValue = null;
  15.         public List<JSONElement> JsonArray = null;

  16.         
  17.         //0 mean [ 1 mean }
  18.         public ItemType ValueType = ItemType.Simple;


  19.         public JsonValueItem()
  20.         {
  21.             this.StrValue = null;
  22.             this.JsonValue = null;
  23.         }
  24.         public JsonValueItem(JSONElement jsonvalue, ItemType withbracket)
  25.         {
  26.             this.ValueType = withbracket;
  27.             this.JsonValue = jsonvalue;
  28.         }
  29.         public JsonValueItem(List<JSONElement> jsonarray)
  30.         {

  31.             this.JsonArray = jsonarray;
  32.         }
  33.         public JsonValueItem(List<JSONElement> jsonarray, ItemType withbracket)
  34.         {
  35.             this.ValueType = withbracket;
  36.             this.JsonArray = jsonarray;
  37.         }

  38.         public override String ToString()
  39.         {
  40.             if (this.StrValue != null)
  41.                 return "\"" + StrValue + "\"";

  42.             if (this.ValueType == ItemType.Dict)
  43.             {
  44.                 String ret = "";
  45.                 ret += "{";
  46.                 String connector = string.Empty;
  47.                 foreach (var v in this.JsonArray)
  48.                 {

  49.                     if (v.ToString() == null)
  50.                         continue;
  51.                     ret += connector;
  52.                     ret += v.ToString();
  53.                     connector = ",";

  54.                 }
  55.                 ret += "}";
  56.                 return ret;
  57.             }

  58.             if (this.JsonArray != null)
  59.             {
  60.                 String ret = "";
  61.                 ret += "[";
  62.                 String connector = string.Empty;
  63.                 foreach (var v in this.JsonArray)
  64.                 {
  65.                     if (v.ToString() == null)
  66.                         continue;
  67.                     ret += connector;
  68.                     ret += v.ToString();
  69.                     connector = ",";
  70.                     
  71.                 }
  72.                 ret += "]";
  73.                 return ret;
  74.             }
  75.             throw new Exception("Unhandled JSON value!!!");
  76.         }


  77.         public object Clone()
  78.         {
  79.             JsonValueItem ret = new JsonValueItem();
  80.             ret.StrValue = this.StrValue;
  81.             ret.ValueType = this.ValueType;
  82.             if (this.JsonValue == null)
  83.                 ret.JsonValue = null;
  84.             else
  85.                 ret.JsonValue = (JSONElement) this.JsonValue.Clone();
  86.             if (this.JsonArray == null)
  87.                 return ret;
  88.             else
  89.             {
  90.                 ret.JsonArray = new List<JSONElement>();
  91.                 foreach (JSONElement je in this.JsonArray)
  92.                     ret.JsonArray.Add((JSONElement)je.Clone());
  93.             }
  94.             return ret;
  95.         }
  96.     }
  97. }
JSONUtils.cs

点击(此处)折叠或打开

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;

  6. namespace JSONMgr
  7. {
  8.     class JsonUtils
  9.     {
  10.         private static void MoveFoward(String content, ref int index)
  11.         {

  12.             while (index < content.Length && (content[index] == ' ' || content[index] == '\r' || content[index] == '\n' || content[index] == ',' || content[index] == '\t'))
  13.                 index++;
  14.         }
  15.         private static String TrimQuot(String input)
  16.         {
  17.             return input.Substring(1, input.Length - 2);
  18.         }

  19.         private static String readkey(String content, ref int index)
  20.         {
  21.             // if it is in string format {"key": "value"}
  22.             MoveFoward(content, ref index);
  23.             if (content[index] == '\"')
  24.             {
  25.                 string ret = ReadStrValue(content, ref index);
  26.                 return TrimQuot(ret);
  27.             }
  28.             //if it is in simple format {key: "value"}
  29.             StringBuilder sb = new StringBuilder();
  30.             while (content[index] != ' ' && content[index] != ':')
  31.             {
  32.                 sb.Append(content[index++]);
  33.             }

  34.             return sb.ToString();
  35.         }
  36.         
  37.         private static String ReadStrValue(string content, ref int index)
  38.         {
  39.             bool isString = false;
  40.             StringBuilder sb = new StringBuilder();
  41.             MoveFoward(content, ref index);
  42.             if (content[index] != '\"')
  43.                 throw new Exception("Not a String");
  44.             sb.Append(content[index]);

  45.             char tmp = ' ';
  46.             isString = true;
  47.             while (isString)
  48.             {
  49.                 index++;
  50.                 sb.Append(content[index]);
  51.                 if (tmp != '\\' && content[index] == '"')
  52.                     isString = false;
  53.                 tmp = content[index];
  54.             }
  55.             index++;
  56.             return sb.ToString();
  57.         }
  58.        
  59.         private static JsonValueItem readvalue(String content, ref int index)
  60.         {
  61.             MoveFoward(content, ref index);
  62.             if (content[index] == '\"')
  63.             {
  64.                 JsonValueItem jv = new JsonValueItem();
  65.                 String strvalue = TrimQuot(ReadStrValue(content, ref index));
  66.                 jv.StrValue = strvalue;
  67.                 jv.ValueType = ItemType.Simple;
  68.                 return jv;
  69.             }
  70.             else
  71.             {
  72.                 JsonValueItem jv = Parser(content, ref index);
  73.                 return jv;
  74.             }

  75.         }

  76.         private static JSONElement ParserItem(String content, ref int index)
  77.         {
  78.             MoveFoward(content, ref index);
  79.             if(content[index] == '{' || content[index] == '['){
  80.                 JsonValueItem tmp = Parser(content, ref index);
  81.                 return new JSONElement(tmp);
  82.             }

  83.             String key = readkey(content, ref index);
  84.             MoveFoward(content, ref index);
  85.             if (content[index] != ':')
  86.             {
  87.                 throw new Exception("Should separate key and value with ':'");
  88.             }
  89.             index++;
  90.             MoveFoward(content, ref index);
  91.             JsonValueItem jv = readvalue(content, ref index);
  92.             MoveFoward(content, ref index);
  93.             return new JSONElement(key, jv);
  94.         }

  95.         private static JsonValueItem ParserArray(String content, ref int index)
  96.         {

  97.             index++;
  98.             List<JSONElement> ret = new List<JSONElement>();
  99.             while (true)
  100.             {
  101.                 MoveFoward(content, ref index);
  102.                 char cur = content[index];
  103.                 if (cur == ']')
  104.                 {
  105.                     index++;
  106.                     break;
  107.                 }
  108.                 ret.Add(ParserItem(content, ref index));
  109.             }
  110.             JsonValueItem jv = new JsonValueItem(ret, ItemType.Array);

  111.             return jv;
  112.         }
  113.     
  114.         public static JsonValueItem Parser(String content)
  115.         {
  116.             int index = 0;
  117.             return Parser(content, ref index);
  118.         }


  119.         private static JsonValueItem ParserElement(String content, ref int index)
  120.         {
  121.             index++;
  122.             MoveFoward(content, ref index);
  123.             List<JSONElement> lj = new List<JSONElement>();
  124.             while (index < content.Length)
  125.             {
  126.                 var tmp = ParserItem(content, ref index);
  127.                 lj.Add(tmp);
  128.                 MoveFoward(content, ref index);
  129.                 if (content[index] == '}')
  130.                 {
  131.                     //withbracket = true;
  132.                     index++;
  133.                     break;
  134.                 }
  135.             }

  136.             JsonValueItem ret = new JsonValueItem(lj,ItemType.Dict);
  137.             return ret;
  138.         }


  139.         private static JsonValueItem Parser(String content, ref int index)
  140.         {
  141.             MoveFoward(content, ref index);
  142.             if (content[index] != '{' && content[index] != '[')
  143.                 throw new Exception("Unhandled!!!" + content[index]);
  144.             if (content[index] == '[')
  145.                 return ParserArray(content, ref index);
  146.             if (content[index] == '{')
  147.             {
  148.                return ParserElement(content, ref index);
  149.                 
  150.             }
  151.             return null;

  152.         }

  153.     }
  154. }




阅读(3340) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~