Unity3D中使用MiniJson解析json的例子

jsonObject:

---------------------------------

{
    "name":"中国",
    "province":[
        {
            "name":"黑龙江",
            "cities":{
                "city":[
                    "哈尔滨",
                    "大庆"
                ]
            }
        },
        {
            "name":"广东",
            "cities":{
                "city":[
                    "广州",
                    "深圳",
                    "珠海"
                ]
            }
        },
        {
            "name":"台湾",
            "cities":{
                "city":[
                    "台北",
                    "高雄"
                ]
            }
        },
        {
            "name":"新疆",
            "cities":{
                "city":[
                    "乌鲁木齐"
                ]
            }
        }
    ]
}

 --------------------------------

 

[csharp] view plaincopy


  1. public class JsonDeserialize   
  2. {  
  3.     protected string url = "http://localhost:8080/AssetBundleData/Web/Singlea/";  
  4. }  


[csharp] view plaincopy


  1. using UnityEngine;  
  2. using System.Collections.Generic;  
  3.   
  4. public class ChinaJsonDeserialize : JsonDeserialize   
  5. {  
  6.     private China _china;  
  7.   
  8.     public China china  
  9.     {  
  10.         get   
  11.         {  
  12.             return _china;  
  13.         }  
  14.     }  
  15.   
  16.     public ChinaJsonDeserialize(string jsonData)  
  17.     {  
  18.         _china = new China();  
  19.         ParseJson(jsonData);  
  20.     }  
  21.   
  22.     void ParseJson(string jsonData)  
  23.     {  
  24.           
  25.         if (string.IsNullOrEmpty(jsonData))  
  26.         {  
  27.             Debug.LogError("ChinaJson is null or empty");  
  28.             return;  
  29.         }   
  30.   
  31.         Dictionary<stringobject> jsonObjects = MiniJSON.Json.Deserialize(jsonData) as Dictionary<stringobject>;  
  32.         _china.chinaName = jsonObjects["name"].ToString();  
  33.         _china.province = new List<Province>();  
  34.   
  35.         List<object> provinceList = jsonObjects["province"as List<object>;  
  36.   
  37.         foreach (var i in provinceList)  
  38.         {  
  39.             Dictionary<stringobject> province = i as Dictionary<stringobject>;  
  40.             Province provinceObj = new Province();  
  41.             provinceObj.provinceName = province["name"].ToString();  
  42.             provinceObj.city = new List<City>();  
  43.   
  44.             Dictionary<stringobject> citesDic = province["cities"as Dictionary<stringobject>;  
  45.   
  46.             List<object> childCitesList = citesDic["city"as List<object>;  
  47.             foreach (var childCity in childCitesList)  
  48.             {  
  49.                 City city = new City();  
  50.                 city.cityName = childCity.ToString();  
  51.   
  52.                 provinceObj.city.Add(city);  
  53.             }  
  54.   
  55.             _china.province.Add(provinceObj);  
  56.         }  
  57.     }  
  58. }  
  59.   
  60. public class China  
  61. {  
  62.     public string chinaName;  
  63.     public List<Province> province;  
  64. }  
  65.   
  66. public class Province  
  67. {  
  68.     public string provinceName;  
  69.     public List<City> city;  
  70. }  
  71.   
  72. public class City  
  73. {  
  74.     public string cityName;  
  75. }  


[csharp] view plaincopy


  1. using UnityEngine;  
  2. using System;  
  3. using System.Collections;  
  4. using System.Collections.Generic;  
  5. using System.IO;  
  6. using System.Text;  
  7.   
  8. namespace MiniJSON {  
  9.      
  10.     public static class Json {  
  11.         /// <summary>  
  12.         /// Parses the string json into a value  
  13.         /// </summary>  
  14.         /// <param name="json">A JSON string.</param>  
  15.         /// <returns>An List<object>, a Dictionary<string, object>, a double, an integer,a string, null, true, or false</returns>  
  16.         public static object Deserialize(string json) {  
  17.             // save the string for debug information  
  18.             if (json == null) {  
  19.                 return null;  
  20.             }  
  21.   
  22.             return Parser.Parse(json);  
  23.         }  
  24.   
  25.         sealed class Parser : IDisposable {  
  26.             const string WHITE_SPACE = " \t\n\r";  
  27.             const string WORD_BREAK = " \t\n\r{}[],:\"";  
  28.   
  29.             enum TOKEN {  
  30.                 NONE,  
  31.                 CURLY_OPEN,  
  32.                 CURLY_CLOSE,  
  33.                 SQUARED_OPEN,  
  34.                 SQUARED_CLOSE,  
  35.                 COLON,  
  36.                 COMMA,  
  37.                 STRING,  
  38.                 NUMBER,  
  39.                 TRUE,  
  40.                 FALSE,  
  41.                 NULL  
  42.             };  
  43.   
  44.             StringReader json;  
  45.   
  46.             Parser(string jsonString) {  
  47.                 json = new StringReader(jsonString);  
  48.             }  
  49.   
  50.             public static object Parse(string jsonString) {  
  51.                 using (var instance = new Parser(jsonString)) {  
  52.                     return instance.ParseValue();  
  53.                 }  
  54.             }  
  55.   
  56.             public void Dispose() {  
  57.                 json.Dispose();  
  58.                 json = null;  
  59.             }  
  60.   
  61.             Dictionary<stringobject> ParseObject() {  
  62.                 Dictionary<stringobject> table = new Dictionary<stringobject>();  
  63.   
  64.                 // ditch opening brace  
  65.                 json.Read();  
  66.   
  67.                 // {  
  68.                 while (true) {  
  69.                     switch (NextToken) {  
  70.                     case TOKEN.NONE:  
  71.                         return null;  
  72.                     case TOKEN.COMMA:  
  73.                         continue;  
  74.                     case TOKEN.CURLY_CLOSE:  
  75.                         return table;  
  76.                     default:  
  77.                         // name  
  78.                         string name = ParseString();  
  79.                         if (name == null) {  
  80.                             return null;  
  81.                         }  
  82.   
  83.                         // :  
  84.                         if (NextToken != TOKEN.COLON) {  
  85.                             return null;  
  86.                         }  
  87.                         // ditch the colon  
  88.                         json.Read();  
  89.   
  90.                         // value  
  91.                         table[name] = ParseValue();  
  92.                         break;  
  93.                     }  
  94.                 }  
  95.             }  
  96.   
  97.             List<object> ParseArray() {  
  98.                 List<object> array = new List<object>();  
  99.   
  100.                 // ditch opening bracket  
  101.                 json.Read();  
  102.   
  103.                 // [  
  104.                 var parsing = true;  
  105.                 while (parsing) {  
  106.                     TOKEN nextToken = NextToken;  
  107.   
  108.                     switch (nextToken) {  
  109.                     case TOKEN.NONE:  
  110.                         return null;  
  111.                     case TOKEN.COMMA:  
  112.                         continue;  
  113.                     case TOKEN.SQUARED_CLOSE:  
  114.                         parsing = false;  
  115.                         break;  
  116.                     default:  
  117.                         object value = ParseByToken(nextToken);  
  118.   
  119.                         array.Add(value);  
  120.                         break;  
  121.                     }  
  122.                 }  
  123.   
  124.                 return array;  
  125.             }  
  126.   
  127.             object ParseValue() {  
  128.                 TOKEN nextToken = NextToken;  
  129.                 return ParseByToken(nextToken);  
  130.             }  
  131.   
  132.             object ParseByToken(TOKEN token) {  
  133.                 switch (token) {  
  134.                 case TOKEN.STRING:  
  135.                     return ParseString();  
  136.                 case TOKEN.NUMBER:  
  137.                     return ParseNumber();  
  138.                 case TOKEN.CURLY_OPEN:  
  139.                     return ParseObject();  
  140.                 case TOKEN.SQUARED_OPEN:  
  141.                     return ParseArray();  
  142.                 case TOKEN.TRUE:  
  143.                     return true;  
  144.                 case TOKEN.FALSE:  
  145.                     return false;  
  146.                 case TOKEN.NULL:  
  147.                     return null;  
  148.                 default:  
  149.                     return null;  
  150.                 }  
  151.             }  
  152.   
  153.             string ParseString() {  
  154.                 StringBuilder s = new StringBuilder();  
  155.                 char c;  
  156.   
  157.                 // ditch opening quote  
  158.                 json.Read();  
  159.   
  160.                 bool parsing = true;  
  161.                 while (parsing) {  
  162.   
  163.                     if (json.Peek() == -1) {  
  164.                         parsing = false;  
  165.                         break;  
  166.                     }  
  167.   
  168.                     c = NextChar;  
  169.                     switch (c) {  
  170.                     case '"':  
  171.                         parsing = false;  
  172.                         break;  
  173.                     case '\\':  
  174.                         if (json.Peek() == -1) {  
  175.                             parsing = false;  
  176.                             break;  
  177.                         }  
  178.   
  179.                         c = NextChar;  
  180.                         switch (c) {  
  181.                         case '"':  
  182.                         case '\\':  
  183.                         case '/':  
  184.                             s.Append(c);  
  185.                             break;  
  186.                         case 'b':  
  187.                             s.Append('\b');  
  188.                             break;  
  189.                         case 'f':  
  190.                             s.Append('\f');  
  191.                             break;  
  192.                         case 'n':  
  193.                             s.Append('\n');  
  194.                             break;  
  195.                         case 'r':  
  196.                             s.Append('\r');  
  197.                             break;  
  198.                         case 't':  
  199.                             s.Append('\t');  
  200.                             break;  
  201.                         case 'u':  
  202.                             var hex = new StringBuilder();  
  203.   
  204.                             for (int i=0; i< 4; i++) {  
  205.                                 hex.Append(NextChar);  
  206.                             }  
  207.   
  208.                             s.Append((char) Convert.ToInt32(hex.ToString(), 16));  
  209.                             break;  
  210.                         }  
  211.                         break;  
  212.                     default:  
  213.                         s.Append(c);  
  214.                         break;  
  215.                     }  
  216.                 }  
  217.   
  218.                 return s.ToString();  
  219.             }  
  220.   
  221.             object ParseNumber() {  
  222.                 string number = NextWord;  
  223.   
  224.                 if (number.IndexOf('.') == -1) {  
  225.                     long parsedInt;  
  226.                     Int64.TryParse(number, out parsedInt);  
  227.                     return parsedInt;  
  228.                 }  
  229.   
  230.                 double parsedDouble;  
  231.                 Double.TryParse(number, out parsedDouble);  
  232.                 return parsedDouble;  
  233.             }  
  234.   
  235.             void EatWhitespace() {  
  236.                 while (WHITE_SPACE.IndexOf(PeekChar) != -1) {  
  237.                     json.Read();  
  238.   
  239.                     if (json.Peek() == -1) {  
  240.                         break;  
  241.                     }  
  242.                 }  
  243.             }  
  244.   
  245.             char PeekChar {  
  246.                 get {  
  247.                     return Convert.ToChar(json.Peek());  
  248.                 }  
  249.             }  
  250.   
  251.             char NextChar {  
  252.                 get {  
  253.                     return Convert.ToChar(json.Read());  
  254.                 }  
  255.             }  
  256.   
  257.             string NextWord {  
  258.                 get {  
  259.                     StringBuilder word = new StringBuilder();  
  260.   
  261.                     while (WORD_BREAK.IndexOf(PeekChar) == -1) {  
  262.                         word.Append(NextChar);  
  263.   
  264.                         if (json.Peek() == -1) {  
  265.                             break;  
  266.                         }  
  267.                     }  
  268.   
  269.                     return word.ToString();  
  270.                 }  
  271.             }  
  272.   
  273.             TOKEN NextToken {  
  274.                 get {  
  275.                     EatWhitespace();  
  276.   
  277.                     if (json.Peek() == -1) {  
  278.                         return TOKEN.NONE;  
  279.                     }  
  280.   
  281.                     char c = PeekChar;  
  282.                     switch (c) {  
  283.                     case '{':  
  284.                         return TOKEN.CURLY_OPEN;  
  285.                     case '}':  
  286.                         json.Read();  
  287.                         return TOKEN.CURLY_CLOSE;  
  288.                     case '[':  
  289.                         return TOKEN.SQUARED_OPEN;  
  290.                     case ']':  
  291.                         json.Read();  
  292.                         return TOKEN.SQUARED_CLOSE;  
  293.                     case ',':  
  294.                         json.Read();  
  295.                         return TOKEN.COMMA;  
  296.                     case '"':  
  297.                         return TOKEN.STRING;  
  298.                     case ':':  
  299.                         return TOKEN.COLON;  
  300.                     case '0':  
  301.                     case '1':  
  302.                     case '2':  
  303.                     case '3':  
  304.                     case '4':  
  305.                     case '5':  
  306.                     case '6':  
  307.                     case '7':  
  308.                     case '8':  
  309.                     case '9':  
  310.                     case '-':  
  311.                         return TOKEN.NUMBER;  
  312.                     }  
  313.   
  314.                     string word = NextWord;  
  315.   
  316.                     switch (word) {  
  317.                     case "false":  
  318.                         return TOKEN.FALSE;  
  319.                     case "true":  
  320.                         return TOKEN.TRUE;  
  321.                     case "null":  
  322.                         return TOKEN.NULL;  
  323.                     }  
  324.   
  325.                     return TOKEN.NONE;  
  326.                 }  
  327.             }  
  328.         }  
  329.   
  330.         /// <summary>  
  331.         /// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string  
  332.         /// </summary>  
  333.         /// <param name="json">A Dictionary<string, object> / List<object></param>  
  334.         /// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>  
  335.         public static string Serialize(object obj) {  
  336.             return Serializer.Serialize(obj);  
  337.         }  
  338.   
  339.         sealed class Serializer {  
  340.             StringBuilder builder;  
  341.   
  342.             Serializer() {  
  343.                 builder = new StringBuilder();  
  344.             }  
  345.   
  346.             public static string Serialize(object obj) {  
  347.                 var instance = new Serializer();  
  348.   
  349.                 instance.SerializeValue(obj);  
  350.   
  351.                 return instance.builder.ToString();  
  352.             }  
  353.   
  354.             void SerializeValue(object value) {  
  355.                 IList asList;  
  356.                 IDictionary asDict;  
  357.                 string asStr;  
  358.   
  359.                 if (value == null) {  
  360.                     builder.Append("null");  
  361.                 }  
  362.                 else if ((asStr = value as string) != null) {  
  363.                     SerializeString(asStr);  
  364.                 }  
  365.                 else if (value is bool) {  
  366.                     builder.Append(value.ToString().ToLower());  
  367.                 }  
  368.                 else if ((asList = value as IList) != null) {  
  369.                     SerializeArray(asList);  
  370.                 }  
  371.                 else if ((asDict = value as IDictionary) != null) {  
  372.                     SerializeObject(asDict);  
  373.                 }  
  374.                 else if (value is char) {  
  375.                     SerializeString(value.ToString());  
  376.                 }  
  377.                 else {  
  378.                     SerializeOther(value);  
  379.                 }  
  380.             }  
  381.   
  382.             void SerializeObject(IDictionary obj) {  
  383.                 bool first = true;  
  384.   
  385.                 builder.Append('{');  
  386.   
  387.                 foreach (object e in obj.Keys) {  
  388.                     if (!first) {  
  389.                         builder.Append(',');  
  390.                     }  
  391.   
  392.                     SerializeString(e.ToString());  
  393.                     builder.Append(':');  
  394.   
  395.                     SerializeValue(obj[e]);  
  396.   
  397.                     first = false;  
  398.                 }  
  399.   
  400.                 builder.Append('}');  
  401.             }  
  402.   
  403.             void SerializeArray(IList anArray) {  
  404.                 builder.Append('[');  
  405.   
  406.                 bool first = true;  
  407.   
  408.                 foreach (object obj in anArray) {  
  409.                     if (!first) {  
  410.                         builder.Append(',');  
  411.                     }  
  412.   
  413.                     SerializeValue(obj);  
  414.   
  415.                     first = false;  
  416.                 }  
  417.   
  418.                 builder.Append(']');  
  419.             }  
  420.   
  421.             void SerializeString(string str) {  
  422.                 builder.Append('\"');  
  423.   
  424.                 char[] charArray = str.ToCharArray();  
  425.                 foreach (var c in charArray) {  
  426.                     switch (c) {  
  427.                     case '"':  
  428.                         builder.Append("\\\"");  
  429.                         break;  
  430.                     case '\\':  
  431.                         builder.Append("\\\\");  
  432.                         break;  
  433.                     case '\b':  
  434.                         builder.Append("\\b");  
  435.                         break;  
  436.                     case '\f':  
  437.                         builder.Append("\\f");  
  438.                         break;  
  439.                     case '\n':  
  440.                         builder.Append("\\n");  
  441.                         break;  
  442.                     case '\r':  
  443.                         builder.Append("\\r");  
  444.                         break;  
  445.                     case '\t':  
  446.                         builder.Append("\\t");  
  447.                         break;  
  448.                     default:  
  449.                         int codepoint = Convert.ToInt32(c);  
  450.                         if ((codepoint >= 32) && (codepoint <= 126)) {  
  451.                             builder.Append(c);  
  452.                         }  
  453.                         else {  
  454.                             builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0'));  
  455.                         }  
  456.                         break;  
  457.                     }  
  458.                 }  
  459.   
  460.                 builder.Append('\"');  
  461.             }  
  462.   
  463.             void SerializeOther(object value) {  
  464.                 if (value is float  
  465.                     || value is int  
  466.                     || value is uint  
  467.                     || value is long  
  468.                     || value is double  
  469.                     || value is sbyte  
  470.                     || value is byte  
  471.                     || value is short  
  472.                     || value is ushort  
  473.                     || value is ulong  
  474.                     || value is decimal) {  
  475.                     builder.Append(value.ToString());  
  476.                 }  
  477.                 else {  
  478.                     SerializeString(value.ToString());  
  479.                 }  
  480.             }  
  481.         }  
  482.     }  
展开阅读全文

没有更多推荐了,返回首页