119 lines
2.3 KiB
C#
119 lines
2.3 KiB
C#
using System;
|
|
using System.Text;
|
|
using sharp.extensions;
|
|
|
|
namespace sharp.json
|
|
{
|
|
public class JSONString : JSON
|
|
{
|
|
static System.Tuple<char,char>[] escapeCharacters = {
|
|
System.Tuple.Create('\\','\\'),
|
|
System.Tuple.Create('/','/'),
|
|
System.Tuple.Create('"','"'),
|
|
System.Tuple.Create('b','\b'),
|
|
System.Tuple.Create('f','\f'),
|
|
System.Tuple.Create('n','\n'),
|
|
System.Tuple.Create('r','\r'),
|
|
System.Tuple.Create('t','\t'),
|
|
};
|
|
|
|
string value;
|
|
|
|
public JSONString()
|
|
:base(JSONTypes.String)
|
|
{
|
|
this.value = "";
|
|
}
|
|
|
|
public JSONString(String value)
|
|
:base(JSONTypes.String)
|
|
{
|
|
this.value = value;
|
|
}
|
|
|
|
public override string String
|
|
{
|
|
get { return this.value; }
|
|
}
|
|
|
|
public override double Double
|
|
{
|
|
get { return Double.Parse(this.value); }
|
|
}
|
|
|
|
public override long Integer
|
|
{
|
|
get { return long.Parse(this.value); }
|
|
}
|
|
|
|
|
|
public override string[] prettyPrint()
|
|
{
|
|
return new string[] { ToString() };
|
|
}
|
|
|
|
public override string ToString()
|
|
{
|
|
return String.Format("\"{0}\"",escape(this.value));
|
|
}
|
|
|
|
public static string escape(string source){
|
|
StringBuilder sb = new StringBuilder();
|
|
foreach (char ch in source){
|
|
if ((ch >= 0x20) && (ch < 128)){
|
|
sb.Append(ch);
|
|
} else if (ch < 0x20){
|
|
foreach (System.Tuple<char,char> repl in escapeCharacters){
|
|
if (repl.Item2 == ch){
|
|
sb.Append("\\");
|
|
sb.Append(repl.Item1);
|
|
break;
|
|
}
|
|
}
|
|
} else {
|
|
int iv = (int)ch;
|
|
sb.Append("\\u");
|
|
sb.Append("____");
|
|
Console.WriteLine("JSON WARNING: UNICODE ESCAPE SEQUENCES ARE NOT IMPLEMENTED YET");
|
|
}
|
|
}
|
|
return sb.ToString();
|
|
}
|
|
|
|
public static string unescape(string source)
|
|
{
|
|
StringBuilder sb = new StringBuilder();
|
|
CharEnumerator ce = source.GetEnumerator();
|
|
char[] hex = new char[4];
|
|
|
|
while (ce.MoveNext()){
|
|
|
|
if (ce.Current == '\\'){
|
|
ce.MoveNext();
|
|
|
|
foreach (System.Tuple<char, char> repl in escapeCharacters)
|
|
{
|
|
if (repl.Item1 == ce.Current)
|
|
{
|
|
sb.Append(repl.Item2);
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (ce.Current == 'u'){
|
|
for (int n = 0; n < 4;n++){
|
|
ce.MoveNext();
|
|
hex[3 - n] = ce.Current;
|
|
}
|
|
sb.Append((char)( HexString.toBytes(hex).toUInt32()[0] ));
|
|
}
|
|
|
|
} else {
|
|
sb.Append(ce.Current);
|
|
}
|
|
}
|
|
return sb.ToString();
|
|
}
|
|
}
|
|
}
|