private static void AddElement(ANode ctx, string token, string tokenName, bool tokenIsString) { if (tokenIsString) { if (token == "@#$%EMPTYSTRING") { token = ""; } if (ctx is Array) { ctx.Add(new Data(token)); } else { ctx.Add(tokenName, new Data(token)); // assume dictionary/object } } else { Data number = Numberize(token, tokenName); if (ctx is Array) { ctx.Add(number); } else { ctx.Add(tokenName, number); } } }
public static ANode Parse(string aJSON) { Stack <ANode> stack = new Stack <ANode>(); ANode ctx = null; int i = 0; string Token = ""; string TokenName = ""; bool QuoteMode = false; bool TokenIsString = false; while (i < aJSON.Length) { switch (aJSON[i]) { case '{': if (QuoteMode) { Token += aJSON[i]; break; } stack.Push(new Class()); if (ctx != null) { TokenName = TokenName.Trim(); if (ctx is Array) { ctx.Add(stack.Peek()); } else if (TokenName != "") { ctx.Add(TokenName, stack.Peek()); } } TokenName = ""; Token = ""; ctx = stack.Peek(); break; case '[': if (QuoteMode) { Token += aJSON[i]; break; } stack.Push(new Array()); if (ctx != null) { TokenName = TokenName.Trim(); if (ctx is Array) { ctx.Add(stack.Peek()); } else if (TokenName != "") { ctx.Add(TokenName, stack.Peek()); } } TokenName = ""; Token = ""; ctx = stack.Peek(); break; case '}': case ']': if (QuoteMode) { Token += aJSON[i]; break; } if (stack.Count == 0) { throw new Exception("JSON Parse: Too many closing brackets"); } stack.Pop(); if (Token != "") { TokenName = TokenName.Trim(); AddElement(ctx, Token, TokenName, TokenIsString); TokenIsString = false; } TokenName = ""; Token = ""; if (stack.Count > 0) { ctx = stack.Peek(); } break; case ':': if (QuoteMode) { Token += aJSON[i]; break; } TokenName = Token; Token = ""; TokenIsString = false; break; case '"': QuoteMode ^= true; TokenIsString = QuoteMode || TokenIsString; if (QuoteMode == false && Token == "") { Token = "@#$%EMPTYSTRING"; } break; case ',': if (QuoteMode) { Token += aJSON[i]; break; } if (Token != "") { AddElement(ctx, Token, TokenName, TokenIsString); } TokenName = ""; Token = ""; TokenIsString = false; break; case '\r': case '\n': break; case ' ': case '\t': if (QuoteMode) { Token += aJSON[i]; } break; case '\\': ++i; if (QuoteMode) { char C = aJSON[i]; switch (C) { case 't': Token += '\t'; break; case 'r': Token += '\r'; break; case 'n': Token += '\n'; break; case 'b': Token += '\b'; break; case 'f': Token += '\f'; break; case 'u': { string s = aJSON.Substring(i + 1, 4); Token += (char)int.Parse(s, NumberStyles.AllowHexSpecifier); i += 4; break; } default: Token += C; break; } } break; default: Token += aJSON[i]; break; } ++i; } if (QuoteMode) { Debug.LogError("JSON Parse: Quotation marks seems to be messed up."); } return(ctx); }