json:

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

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

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

public class JsonDeserialize
{
protected string url = "http://localhost:8080/AssetBundleData/Web/Singlea/";
}
using UnityEngine;
using System.Collections.Generic; public class ChinaJsonDeserialize : JsonDeserialize
{
private China _china; public China china
{
get
{
return _china;
}
} public ChinaJsonDeserialize(string jsonData)
{
_china = new China();
ParseJson(jsonData);
} void ParseJson(string jsonData)
{ if (string.IsNullOrEmpty(jsonData))
{
Debug.LogError("ChinaJson is null or empty");
return;
} Dictionary<string, object> jsonObjects = MiniJSON.Json.Deserialize(jsonData) as Dictionary<string, object>;
_china.chinaName = jsonObjects["name"].ToString();
_china.province = new List<Province>(); List<object> provinceList = jsonObjects["province"] as List<object>; foreach (var i in provinceList)
{
Dictionary<string, object> province = i as Dictionary<string, object>;
Province provinceObj = new Province();
provinceObj.provinceName = province["name"].ToString();
provinceObj.city = new List<City>(); Dictionary<string, object> citesDic = province["cities"] as Dictionary<string, object>; List<object> childCitesList = citesDic["city"] as List<object>;
foreach (var childCity in childCitesList)
{
City city = new City();
city.cityName = childCity.ToString(); provinceObj.city.Add(city);
} _china.province.Add(provinceObj);
}
}
} public class China
{
public string chinaName;
public List<Province> province;
} public class Province
{
public string provinceName;
public List<City> city;
} public class City
{
public string cityName;
}
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text; namespace MiniJSON { public static class Json {
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An List<object>, a Dictionary<string, object>, a double, an integer,a string, null, true, or false</returns>
public static object Deserialize(string json) {
// save the string for debug information
if (json == null) {
return null;
} return Parser.Parse(json);
} sealed class Parser : IDisposable {
const string WHITE_SPACE = " \t\n\r";
const string WORD_BREAK = " \t\n\r{}[],:\""; enum TOKEN {
NONE,
CURLY_OPEN,
CURLY_CLOSE,
SQUARED_OPEN,
SQUARED_CLOSE,
COLON,
COMMA,
STRING,
NUMBER,
TRUE,
FALSE,
NULL
}; StringReader json; Parser(string jsonString) {
json = new StringReader(jsonString);
} public static object Parse(string jsonString) {
using (var instance = new Parser(jsonString)) {
return instance.ParseValue();
}
} public void Dispose() {
json.Dispose();
json = null;
} Dictionary<string, object> ParseObject() {
Dictionary<string, object> table = new Dictionary<string, object>(); // ditch opening brace
json.Read(); // {
while (true) {
switch (NextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.CURLY_CLOSE:
return table;
default:
// name
string name = ParseString();
if (name == null) {
return null;
} // :
if (NextToken != TOKEN.COLON) {
return null;
}
// ditch the colon
json.Read(); // value
table[name] = ParseValue();
break;
}
}
} List<object> ParseArray() {
List<object> array = new List<object>(); // ditch opening bracket
json.Read(); // [
var parsing = true;
while (parsing) {
TOKEN nextToken = NextToken; switch (nextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.SQUARED_CLOSE:
parsing = false;
break;
default:
object value = ParseByToken(nextToken); array.Add(value);
break;
}
} return array;
} object ParseValue() {
TOKEN nextToken = NextToken;
return ParseByToken(nextToken);
} object ParseByToken(TOKEN token) {
switch (token) {
case TOKEN.STRING:
return ParseString();
case TOKEN.NUMBER:
return ParseNumber();
case TOKEN.CURLY_OPEN:
return ParseObject();
case TOKEN.SQUARED_OPEN:
return ParseArray();
case TOKEN.TRUE:
return true;
case TOKEN.FALSE:
return false;
case TOKEN.NULL:
return null;
default:
return null;
}
} string ParseString() {
StringBuilder s = new StringBuilder();
char c; // ditch opening quote
json.Read(); bool parsing = true;
while (parsing) { if (json.Peek() == -1) {
parsing = false;
break;
} c = NextChar;
switch (c) {
case '"':
parsing = false;
break;
case '\\':
if (json.Peek() == -1) {
parsing = false;
break;
} c = NextChar;
switch (c) {
case '"':
case '\\':
case '/':
s.Append(c);
break;
case 'b':
s.Append('\b');
break;
case 'f':
s.Append('\f');
break;
case 'n':
s.Append('\n');
break;
case 'r':
s.Append('\r');
break;
case 't':
s.Append('\t');
break;
case 'u':
var hex = new StringBuilder(); for (int i=0; i< 4; i++) {
hex.Append(NextChar);
} s.Append((char) Convert.ToInt32(hex.ToString(), 16));
break;
}
break;
default:
s.Append(c);
break;
}
} return s.ToString();
} object ParseNumber() {
string number = NextWord; if (number.IndexOf('.') == -1) {
long parsedInt;
Int64.TryParse(number, out parsedInt);
return parsedInt;
} double parsedDouble;
Double.TryParse(number, out parsedDouble);
return parsedDouble;
} void EatWhitespace() {
while (WHITE_SPACE.IndexOf(PeekChar) != -1) {
json.Read(); if (json.Peek() == -1) {
break;
}
}
} char PeekChar {
get {
return Convert.ToChar(json.Peek());
}
} char NextChar {
get {
return Convert.ToChar(json.Read());
}
} string NextWord {
get {
StringBuilder word = new StringBuilder(); while (WORD_BREAK.IndexOf(PeekChar) == -1) {
word.Append(NextChar); if (json.Peek() == -1) {
break;
}
} return word.ToString();
}
} TOKEN NextToken {
get {
EatWhitespace(); if (json.Peek() == -1) {
return TOKEN.NONE;
} char c = PeekChar;
switch (c) {
case '{':
return TOKEN.CURLY_OPEN;
case '}':
json.Read();
return TOKEN.CURLY_CLOSE;
case '[':
return TOKEN.SQUARED_OPEN;
case ']':
json.Read();
return TOKEN.SQUARED_CLOSE;
case ',':
json.Read();
return TOKEN.COMMA;
case '"':
return TOKEN.STRING;
case ':':
return TOKEN.COLON;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
return TOKEN.NUMBER;
} string word = NextWord; switch (word) {
case "false":
return TOKEN.FALSE;
case "true":
return TOKEN.TRUE;
case "null":
return TOKEN.NULL;
} return TOKEN.NONE;
}
}
} /// <summary>
/// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string
/// </summary>
/// <param name="json">A Dictionary<string, object> / List<object></param>
/// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
public static string Serialize(object obj) {
return Serializer.Serialize(obj);
} sealed class Serializer {
StringBuilder builder; Serializer() {
builder = new StringBuilder();
} public static string Serialize(object obj) {
var instance = new Serializer(); instance.SerializeValue(obj); return instance.builder.ToString();
} void SerializeValue(object value) {
IList asList;
IDictionary asDict;
string asStr; if (value == null) {
builder.Append("null");
}
else if ((asStr = value as string) != null) {
SerializeString(asStr);
}
else if (value is bool) {
builder.Append(value.ToString().ToLower());
}
else if ((asList = value as IList) != null) {
SerializeArray(asList);
}
else if ((asDict = value as IDictionary) != null) {
SerializeObject(asDict);
}
else if (value is char) {
SerializeString(value.ToString());
}
else {
SerializeOther(value);
}
} void SerializeObject(IDictionary obj) {
bool first = true; builder.Append('{'); foreach (object e in obj.Keys) {
if (!first) {
builder.Append(',');
} SerializeString(e.ToString());
builder.Append(':'); SerializeValue(obj[e]); first = false;
} builder.Append('}');
} void SerializeArray(IList anArray) {
builder.Append('['); bool first = true; foreach (object obj in anArray) {
if (!first) {
builder.Append(',');
} SerializeValue(obj); first = false;
} builder.Append(']');
} void SerializeString(string str) {
builder.Append('\"'); char[] charArray = str.ToCharArray();
foreach (var c in charArray) {
switch (c) {
case '"':
builder.Append("\\\"");
break;
case '\\':
builder.Append("\\\\");
break;
case '\b':
builder.Append("\\b");
break;
case '\f':
builder.Append("\\f");
break;
case '\n':
builder.Append("\\n");
break;
case '\r':
builder.Append("\\r");
break;
case '\t':
builder.Append("\\t");
break;
default:
int codepoint = Convert.ToInt32(c);
if ((codepoint >= 32) && (codepoint <= 126)) {
builder.Append(c);
}
else {
builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0'));
}
break;
}
} builder.Append('\"');
} void SerializeOther(object value) {
if (value is float
|| value is int
|| value is uint
|| value is long
|| value is double
|| value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is ulong
|| value is decimal) {
builder.Append(value.ToString());
}
else {
SerializeString(value.ToString());
}
}
}
}
}

Unity3D中使用MiniJson解析json的例子的更多相关文章

  1. Android中使用Gson解析JSON数据的两种方法

    Json是一种类似于XML的通用数据交换格式,具有比XML更高的传输效率;本文将介绍两种方法解析JSON数据,需要的朋友可以参考下   Json是一种类似于XML的通用数据交换格式,具有比XML更高的 ...

  2. 转:JS中生成和解析JSON

    原文地址:JS中生成和解析JSON 1.JS中生成JSON对象的方法: var json = []; var row1 = {}; row1.id= "1"; row1.name ...

  3. Android中使用Gson解析JSON数据

      Android中使用Gson解析JSON数据 在Android中可以使用Gson解析JSON数据 首先,从 code.google.com/p/google-gson/downloads/list ...

  4. Scala中使用fastJson 解析json字符串

    Scala中使用fastJson 解析json字符串 添加依赖 2.解析json字符 2.1可以通过JSON中的parseObject方法,把json字符转转换为一个JSONObject对象 2.2然 ...

  5. 使用QtScript库解析Json数组例子

    本文转载自:http://blog.sina.com.cn/s/blog_671732440100uwxh.html 使用qtscipt库解析json数组首先在工程文件中加 QT        += ...

  6. Delphi中使用ISuperObject解析Json数据

    Java.Php等语言中都有成熟的框架来解析Json数据,可以让我们使用很少的代码就把格式化好的json数据转换成程序可识别的对象或者属性,同时delphi中也有这样的组件来实现此功能,即Isuper ...

  7. JS中生成和解析JSON

    1.JS中生成JSON对象的方法: var json = []; var row1 = {}; row1.id= "1"; row1.name = "jyy"; ...

  8. 在Unity中使用LitJson解析json文件

    LitJson 这个库需要找资源,找到LitJson.dll后将它放在Assets文件夹下,在脚本中使用using引入即可 测试代码 json文件: {"Archice":[{&q ...

  9. Qt简单的解析Json数据例子(一)

    要解析的json的格式为: { "rootpath": "001", "usernum": 111, "childdep" ...

随机推荐

  1. itext之pdf导出添加水印Java工具类

    import java.io.IOException; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentExce ...

  2. MySQL中group_concat函数-和group by配合使用

    MySQL中group_concat函数 完整的语法如下: group_concat([DISTINCT] 要连接的字段 [Order BY ASC/DESC 排序字段] [Separator '分隔 ...

  3. 接口自动化测试:参数化封装(excel文件读取)

    log4j.properties文件配置 log4j.rootLogger = DEBUG,stdout,F log4j.appender.stdout = org.apache.log4j.Cons ...

  4. 使用c#给outlook添加任务、发送邮件

    原文:使用c#给outlook添加任务.发送邮件 c#在使用outlook提供的一些API时,需要将outlook相关的com引用到项目中. 具体方法就是用vs打开工程后,在工程上添加引用,在com选 ...

  5. c#分部类型详解

    一.先看代码来理解 代码一 class ClassA { void A(){;} void B(){;} } 代码二 partial class ClassA { void A(){;} } part ...

  6. 2.4 LINQ中使用where子句指定筛选条件

    本篇讲解的内容有: 使用where筛选过滤LINQ查询 带逻辑的where筛选 多个where筛选子句 [1.使用where筛选过滤LINQ查询] 通常一个LINQ查询不会如前面的示例代码这么简单,经 ...

  7. VMware7安装CentOS6.5教程

    VMware7安装CentOS6.5教程 http://www.91linux.com/html/2014/CentOS_0415/9727.html工欲善其事,必先利其器.学习linux系统,必须先 ...

  8. Java集合之HashMap源码实现分析

    1.简介 通过上面的一篇随笔我们知道了HashSet的底层是采用Map实现的,那么Map是什么?它的底层又是如何实现的呢?这下我们来分析下源码,看看具体的结构与实现.Map 集合类用于存储元素对(称作 ...

  9. 使用JasperReport+iReport进行Web报表开发

    使用JasperReport+iReport进行Web报表开发 前言 在实际工程中非常,报告是其中很重要的一部分,结果以报表的形式呈现出来.这里所提到的报表可不是简单的二维表,而是拥有复杂表头的.多维 ...

  10. C#快速随机按行读取大型文本文件

    原文:C#快速随机按行读取大型文本文件 下面是我实现的一个数据文件随机读取类,可以随机读取大型文本文件的某一行.在我机器上对一个130MB的文本文件,读取第200000的速度从传统做法的400ms提高 ...