using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace BestHTTP.JSON
{
///
/// Based on the download from http://techblog.procurios.nl/k/news/view/14605/14863/how-do-i-write-my-own-parser-%28for-json%29.html
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes List and Dictionary.
/// All numbers are parsed to doubles.
///
public class Json
{
private const int TOKEN_NONE = 0;
private const int TOKEN_CURLY_OPEN = 1;
private const int TOKEN_CURLY_CLOSE = 2;
private const int TOKEN_SQUARED_OPEN = 3;
private const int TOKEN_SQUARED_CLOSE = 4;
private const int TOKEN_COLON = 5;
private const int TOKEN_COMMA = 6;
private const int TOKEN_STRING = 7;
private const int TOKEN_NUMBER = 8;
private const int TOKEN_TRUE = 9;
private const int TOKEN_FALSE = 10;
private const int TOKEN_NULL = 11;
private const int BUILDER_CAPACITY = 2000;
///
/// Parses the string json into a value
///
/// A JSON string.
/// A List, a Dictionary, a double, a string, null, true, or false
public static object Decode(string json)
{
bool success = true;
return Decode(json, ref success);
}
///
/// Parses the string json into a value; and fills 'success' with the successfullness of the parse.
///
/// A JSON string.
/// Successful parse?
/// A List, a Dictionary, a double, a string, null, true, or false
public static object Decode(string json, ref bool success)
{
success = true;
if (json != null) {
char[] charArray = json.ToCharArray();
int index = 0;
object value = ParseValue(charArray, ref index, ref success);
return value;
} else {
return null;
}
}
///
/// Converts a Dictionary / List object into a JSON string
///
/// A Dictionary / List
/// A JSON encoded string, or null if object 'json' is not serializable
public static string Encode(object json)
{
StringBuilder builder = new StringBuilder(BUILDER_CAPACITY);
bool success = SerializeValue(json, builder);
return (success ? builder.ToString() : null);
}
protected static Dictionary ParseObject(char[] json, ref int index, ref bool success)
{
Dictionary table = new Dictionary();
int token;
// {
NextToken(json, ref index);
bool done = false;
while (!done) {
token = LookAhead(json, index);
if (token == Json.TOKEN_NONE) {
success = false;
return null;
} else if (token == Json.TOKEN_COMMA) {
NextToken(json, ref index);
} else if (token == Json.TOKEN_CURLY_CLOSE) {
NextToken(json, ref index);
return table;
} else {
// name
string name = ParseString(json, ref index, ref success);
if (!success) {
success = false;
return null;
}
// :
token = NextToken(json, ref index);
if (token != Json.TOKEN_COLON) {
success = false;
return null;
}
// value
object value = ParseValue(json, ref index, ref success);
if (!success) {
success = false;
return null;
}
table[name] = value;
}
}
return table;
}
protected static List