Compare commits

..

10 Commits

Author SHA1 Message Date
d6b6a365c7 make miror to github.com 2021-08-22 00:32:36 +02:00
9eb978caea Make netcore as default, also using 3.1 now 2021-01-09 00:19:58 +01:00
875248bcdc Typo 2019-11-29 14:43:26 +01:00
420831eb52 Add netcore 2019-11-24 20:43:32 +01:00
cab3ec2d06 Refactoring and fixing a bug when add json text 2019-07-24 17:07:28 +02:00
aae12f70d3 ref, and change project settings 2019-07-24 13:00:06 +02:00
59b7ead200 and move on 2019-07-23 17:15:23 +02:00
81b0cb3990 make it nice 2019-07-23 14:04:06 +02:00
021417c029 Add Copyright and Readme 2019-05-29 19:17:16 +02:00
853958acda Lineendings 2019-03-07 15:08:21 +01:00
17 changed files with 2485 additions and 2876 deletions

31
COPYING Normal file
View File

@ -0,0 +1,31 @@
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
Thank you for reading this notice. Following the tradition of other public
domain projects, here's a blessing:
May you find forgiveness for yourself and forgive others.
May you experience and share the gift of unconditional love.
May you see light, wherever the illusion of darkness appears.

4
README.md Normal file
View File

@ -0,0 +1,4 @@
# LitJSON
Based on https://github.com/LitJSON/litjson
Maybe you find this Repo on Github. This is a mirror from [here](https://git.blubbfish.net/vs_librarys/litjson).

25
litjson-4.7.1.sln Normal file
View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27004.2010
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "litjson_4.7.1", "litjson\litjson_4.7.1.csproj", "{91A14CD2-2940-4500-8193-56D37EDDDBAA}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{91A14CD2-2940-4500-8193-56D37EDDDBAA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{91A14CD2-2940-4500-8193-56D37EDDDBAA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{91A14CD2-2940-4500-8193-56D37EDDDBAA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{91A14CD2-2940-4500-8193-56D37EDDDBAA}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {AF2398AC-1EAA-4615-B21A-33C68CD44849}
EndGlobalSection
EndGlobal

View File

@ -1,9 +1,9 @@
 
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15 # Visual Studio Version 16
VisualStudioVersion = 15.0.27004.2010 VisualStudioVersion = 16.0.29519.87
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "litjson_4.7.1", "litjson\litjson_4.7.1.csproj", "{91A14CD2-2940-4500-8193-56D37EDDDBAA}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "litjson", "litjson\litjson.csproj", "{244B45C3-E7A0-428B-8AF2-E992FA9E5964}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -11,15 +11,15 @@ Global
Release|Any CPU = Release|Any CPU Release|Any CPU = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution GlobalSection(ProjectConfigurationPlatforms) = postSolution
{91A14CD2-2940-4500-8193-56D37EDDDBAA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {244B45C3-E7A0-428B-8AF2-E992FA9E5964}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{91A14CD2-2940-4500-8193-56D37EDDDBAA}.Debug|Any CPU.Build.0 = Debug|Any CPU {244B45C3-E7A0-428B-8AF2-E992FA9E5964}.Debug|Any CPU.Build.0 = Debug|Any CPU
{91A14CD2-2940-4500-8193-56D37EDDDBAA}.Release|Any CPU.ActiveCfg = Release|Any CPU {244B45C3-E7A0-428B-8AF2-E992FA9E5964}.Release|Any CPU.ActiveCfg = Release|Any CPU
{91A14CD2-2940-4500-8193-56D37EDDDBAA}.Release|Any CPU.Build.0 = Release|Any CPU {244B45C3-E7A0-428B-8AF2-E992FA9E5964}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
EndGlobalSection EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {AF2398AC-1EAA-4615-B21A-33C68CD44849} SolutionGuid = {E215FE79-F42D-4A58-B702-EC7E8AAFADFF}
EndGlobalSection EndGlobalSection
EndGlobal EndGlobal

View File

@ -0,0 +1,8 @@
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.
using System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage("Style", "IDE0038:Musterabgleich verwenden", Justification = "<Ausstehend>", Scope = "member", Target = "~M:LitJson.JsonMapper.WriteValue(System.Object,LitJson.JsonWriter,System.Boolean,System.Int32)")]

View File

@ -11,50 +11,47 @@
#endregion #endregion
using System;
using System.Collections; using System.Collections;
using System.Collections.Specialized; using System.Collections.Specialized;
namespace LitJson namespace LitJson {
{ public enum JsonType {
public enum JsonType None,
{ Object,
None, Array,
String,
Object, Int,
Array, Long,
String, Double,
Int, Boolean
Long, }
Double,
Boolean public interface IJsonWrapper : IList, IOrderedDictionary {
} Boolean IsArray { get; }
Boolean IsBoolean { get; }
public interface IJsonWrapper : IList, IOrderedDictionary Boolean IsDouble { get; }
{ Boolean IsInt { get; }
bool IsArray { get; } Boolean IsLong { get; }
bool IsBoolean { get; } Boolean IsObject { get; }
bool IsDouble { get; } Boolean IsString { get; }
bool IsInt { get; }
bool IsLong { get; } Boolean GetBoolean();
bool IsObject { get; } Double GetDouble();
bool IsString { get; } Int32 GetInt();
JsonType GetJsonType();
bool GetBoolean (); Int64 GetLong();
double GetDouble (); String GetString();
int GetInt ();
JsonType GetJsonType (); void SetBoolean(Boolean val);
long GetLong (); void SetDouble(Double val);
string GetString (); void SetInt(Int32 val);
void SetJsonType(JsonType type);
void SetBoolean (bool val); void SetLong(Int64 val);
void SetDouble (double val); void SetString(String val);
void SetInt (int val);
void SetJsonType (JsonType type); String ToJson();
void SetLong (long val); void ToJson(JsonWriter writer);
void SetString (string val); }
string ToJson ();
void ToJson (JsonWriter writer);
}
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,65 +1,37 @@
#region Header #region Header
/** /**
* JsonException.cs * JsonException.cs
* Base class throwed by LitJSON when a parsing error occurs. * Base class throwed by LitJSON when a parsing error occurs.
* *
* The authors disclaim copyright to this source code. For more details, see * The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution. * the COPYING file included with this distribution.
**/ **/
#endregion #endregion
using System; using System;
namespace LitJson namespace LitJson {
{ public class JsonException :
public class JsonException : #if NETSTANDARD1_5
#if NETSTANDARD1_5 Exception
Exception #else
#else ApplicationException
ApplicationException #endif
#endif {
{ public JsonException() : base() { }
public JsonException () : base ()
{ internal JsonException(ParserToken token) : base(String.Format("Invalid token '{0}' in input string", token)) { }
}
internal JsonException(ParserToken token, Exception inner_exception) : base(String.Format("Invalid token '{0}' in input string", token), inner_exception) { }
internal JsonException (ParserToken token) :
base (String.Format ( internal JsonException(Int32 c) : base(String.Format("Invalid character '{0}' in input string", (Char)c)) { }
"Invalid token '{0}' in input string", token))
{ internal JsonException(Int32 c, Exception inner_exception) : base(String.Format("Invalid character '{0}' in input string", (Char)c), inner_exception) { }
}
public JsonException(String message) : base(message) { }
internal JsonException (ParserToken token,
Exception inner_exception) : public JsonException(String message, Exception inner_exception) : base(message, inner_exception) { }
base (String.Format ( }
"Invalid token '{0}' in input string", token), }
inner_exception)
{
}
internal JsonException (int c) :
base (String.Format (
"Invalid character '{0}' in input string", (char) c))
{
}
internal JsonException (int c, Exception inner_exception) :
base (String.Format (
"Invalid character '{0}' in input string", (char) c),
inner_exception)
{
}
public JsonException (string message) : base (message)
{
}
public JsonException (string message, Exception inner_exception) :
base (message, inner_exception)
{
}
}
}

View File

@ -28,15 +28,8 @@ namespace LitJson {
private Type element_type; private Type element_type;
public Type ElementType { public Type ElementType {
get { get => this.element_type ?? typeof(JsonData);
if (this.element_type == null) { set => this.element_type = value;
return typeof(JsonData);
}
return this.element_type;
}
set { this.element_type = value; }
} }
public Boolean IsArray { get; set; } public Boolean IsArray { get; set; }
@ -48,15 +41,8 @@ namespace LitJson {
private Type element_type; private Type element_type;
public Type ElementType { public Type ElementType {
get { get => this.element_type ?? typeof(JsonData);
if (this.element_type == null) { set => this.element_type = value;
return typeof(JsonData);
}
return this.element_type;
}
set { this.element_type = value; }
} }
public Boolean IsDictionary { get; set; } public Boolean IsDictionary { get; set; }
@ -64,7 +50,6 @@ namespace LitJson {
public IDictionary<String, PropertyMetadata> Properties { get; set; } public IDictionary<String, PropertyMetadata> Properties { get; set; }
} }
internal delegate void ExporterFunc(Object obj, JsonWriter writer); internal delegate void ExporterFunc(Object obj, JsonWriter writer);
public delegate void ExporterFunc<T>(T obj, JsonWriter writer); public delegate void ExporterFunc<T>(T obj, JsonWriter writer);
@ -291,15 +276,15 @@ namespace LitJson {
Type value_type = underlying_type ?? inst_type; Type value_type = underlying_type ?? inst_type;
if (reader.Token == JsonToken.Null) { if (reader.Token == JsonToken.Null) {
#if NETSTANDARD1_5 #if NETSTANDARD1_5
if (inst_type.IsClass() || underlying_type != null) { if (inst_type.IsClass() || underlying_type != null) {
return null; return null;
} }
#else #else
if (inst_type.IsClass || underlying_type != null) { if (inst_type.IsClass || underlying_type != null) {
return null; return null;
} }
#endif #endif
throw new JsonException(String.Format("Can't assign null to an instance of type {0}", inst_type)); throw new JsonException(String.Format("Can't assign null to an instance of type {0}", inst_type));
} }
@ -339,14 +324,15 @@ namespace LitJson {
} }
// Maybe it's an enum // Maybe it's an enum
#if NETSTANDARD1_5 #if NETSTANDARD1_5
if (value_type.IsEnum()) if (value_type.IsEnum()) {
return Enum.ToObject (value_type, reader.Value); return Enum.ToObject (value_type, reader.Value);
#else }
if (value_type.IsEnum) { #else
return Enum.ToObject(value_type, reader.Value); if (value_type.IsEnum) {
} return Enum.ToObject(value_type, reader.Value);
#endif }
#endif
// Try using an implicit conversion operator // Try using an implicit conversion operator
MethodInfo conv_op = GetConvOp(value_type, json_type); MethodInfo conv_op = GetConvOp(value_type, json_type);
@ -450,7 +436,7 @@ namespace LitJson {
} }
private static IJsonWrapper ReadValue(WrapperFactory factory, JsonReader reader) { private static IJsonWrapper ReadValue(WrapperFactory factory, JsonReader reader) {
reader.Read(); _ = reader.Read();
if (reader.Token == JsonToken.ArrayEnd || if (reader.Token == JsonToken.ArrayEnd ||
reader.Token == JsonToken.Null) { reader.Token == JsonToken.Null) {
@ -492,13 +478,13 @@ namespace LitJson {
if (item == null && reader.Token == JsonToken.ArrayEnd) { if (item == null && reader.Token == JsonToken.ArrayEnd) {
break; break;
} }
instance.Add(item); _ = instance.Add(item);
} }
} else if (reader.Token == JsonToken.ObjectStart) { } else if (reader.Token == JsonToken.ObjectStart) {
instance.SetJsonType(JsonType.Object); instance.SetJsonType(JsonType.Object);
while (true) { while (true) {
reader.Read(); _ = reader.Read();
if (reader.Token == JsonToken.ObjectEnd) { if (reader.Token == JsonToken.ObjectEnd) {
break; break;
@ -514,9 +500,7 @@ namespace LitJson {
return instance; return instance;
} }
private static void ReadSkip(JsonReader reader) { private static void ReadSkip(JsonReader reader) => ToWrapper(delegate { return new JsonMockWrapper(); }, reader);
ToWrapper(delegate { return new JsonMockWrapper(); }, reader);
}
private static void RegisterBaseExporters() { private static void RegisterBaseExporters() {
base_exporters_table[typeof(Byte)] = delegate (Object obj, JsonWriter writer) { base_exporters_table[typeof(Byte)] = delegate (Object obj, JsonWriter writer) {
@ -643,7 +627,10 @@ namespace LitJson {
if (obj is IJsonWrapper) { if (obj is IJsonWrapper) {
if (writer_is_private) { if (writer_is_private) {
writer.TextWriter.Write(((IJsonWrapper)obj).ToJson()); String t = ((IJsonWrapper)obj).ToJson();
writer.WriteJson(t);
//writer.TextWriter.Write(t);
//this.context.ExpectingValue = false;
} else { } else {
((IJsonWrapper)obj).ToJson(writer); ((IJsonWrapper)obj).ToJson(writer);
} }
@ -769,7 +756,6 @@ namespace LitJson {
} }
#endregion #endregion
public static String ToJson(Object obj) { public static String ToJson(Object obj) {
lock (static_writer_lock) { lock (static_writer_lock) {
static_writer.Reset(); static_writer.Reset();
@ -780,78 +766,32 @@ namespace LitJson {
} }
} }
public static void ToJson(Object obj, JsonWriter writer) { public static void ToJson(Object obj, JsonWriter writer) => WriteValue(obj, writer, false, 0);
WriteValue(obj, writer, false, 0);
}
public static JsonData ToObject(JsonReader reader) { public static JsonData ToObject(JsonReader reader) => (JsonData)ToWrapper(delegate { return new JsonData(); }, reader);
return (JsonData)ToWrapper(delegate { return new JsonData(); }, reader);
}
public static JsonData ToObject(TextReader reader) { public static JsonData ToObject(TextReader reader) => (JsonData)ToWrapper(delegate { return new JsonData(); }, new JsonReader(reader));
JsonReader json_reader = new JsonReader(reader);
return (JsonData)ToWrapper(delegate { return new JsonData(); }, json_reader); public static JsonData ToObject(String json) => (JsonData)ToWrapper(delegate { return new JsonData(); }, json);
}
public static JsonData ToObject(String json) { public static T ToObject<T>(JsonReader reader) => (T)ReadValue(typeof(T), reader);
return (JsonData)ToWrapper(delegate { return new JsonData(); }, json);
}
public static T ToObject<T>(JsonReader reader) { public static T ToObject<T>(TextReader reader) => (T)ReadValue(typeof(T), new JsonReader(reader));
return (T)ReadValue(typeof(T), reader);
}
public static T ToObject<T>(TextReader reader) { public static T ToObject<T>(String json) => (T)ReadValue(typeof(T), new JsonReader(json));
JsonReader json_reader = new JsonReader(reader);
return (T)ReadValue(typeof(T), json_reader); public static Object ToObject(String json, Type ConvertType) => ReadValue(ConvertType, new JsonReader(json));
}
public static T ToObject<T>(String json) { public static IJsonWrapper ToWrapper(WrapperFactory factory, JsonReader reader) => ReadValue(factory, reader);
JsonReader reader = new JsonReader(json);
return (T)ReadValue(typeof(T), reader); public static IJsonWrapper ToWrapper(WrapperFactory factory, String json) => ReadValue(factory, new JsonReader(json));
}
public static Object ToObject(String json, Type ConvertType) { public static void RegisterExporter<T>(ExporterFunc<T> exporter) => custom_exporters_table[typeof(T)] = (Object obj, JsonWriter writer) => exporter((T)obj, writer);
JsonReader reader = new JsonReader(json);
return ReadValue(ConvertType, reader); public static void RegisterImporter<TJson, TValue>(ImporterFunc<TJson, TValue> importer) => RegisterImporter(custom_importers_table, typeof(TJson), typeof(TValue), (Object input) => importer((TJson)input));
}
public static IJsonWrapper ToWrapper(WrapperFactory factory, JsonReader reader) { public static void UnregisterExporters() => custom_exporters_table.Clear();
return ReadValue(factory, reader);
}
public static IJsonWrapper ToWrapper(WrapperFactory factory, String json) { public static void UnregisterImporters() => custom_importers_table.Clear();
JsonReader reader = new JsonReader(json);
return ReadValue(factory, reader);
}
public static void RegisterExporter<T>(ExporterFunc<T> exporter) {
ExporterFunc exporter_wrapper = delegate (Object obj, JsonWriter writer) {
exporter((T)obj, writer);
};
custom_exporters_table[typeof(T)] = exporter_wrapper;
}
public static void RegisterImporter<TJson, TValue>(ImporterFunc<TJson, TValue> importer) {
ImporterFunc importer_wrapper = delegate (Object input) {
return importer((TJson)input);
};
RegisterImporter(custom_importers_table, typeof(TJson), typeof(TValue), importer_wrapper);
}
public static void UnregisterExporters() {
custom_exporters_table.Clear();
}
public static void UnregisterImporters() {
custom_importers_table.Clear();
}
} }
} }

View File

@ -1,105 +1,132 @@
#region Header #region Header
/** /**
* JsonMockWrapper.cs * JsonMockWrapper.cs
* Mock object implementing IJsonWrapper, to facilitate actions like * Mock object implementing IJsonWrapper, to facilitate actions like
* skipping data more efficiently. * skipping data more efficiently.
* *
* The authors disclaim copyright to this source code. For more details, see * The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution. * the COPYING file included with this distribution.
**/ **/
#endregion #endregion
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Specialized; using System.Collections.Specialized;
namespace LitJson namespace LitJson {
{ public class JsonMockWrapper : IJsonWrapper {
public class JsonMockWrapper : IJsonWrapper public Boolean IsArray => false;
{
public bool IsArray { get { return false; } } public Boolean IsBoolean => false;
public bool IsBoolean { get { return false; } }
public bool IsDouble { get { return false; } } public Boolean IsDouble => false;
public bool IsInt { get { return false; } }
public bool IsLong { get { return false; } } public Boolean IsInt => false;
public bool IsObject { get { return false; } }
public bool IsString { get { return false; } } public Boolean IsLong => false;
public bool GetBoolean () { return false; } public Boolean IsObject => false;
public double GetDouble () { return 0.0; }
public int GetInt () { return 0; } public Boolean IsString => false;
public JsonType GetJsonType () { return JsonType.None; }
public long GetLong () { return 0L; } public Boolean GetBoolean() => false;
public string GetString () { return ""; }
public Double GetDouble() => 0.0;
public void SetBoolean (bool val) {}
public void SetDouble (double val) {} public Int32 GetInt() => 0;
public void SetInt (int val) {}
public void SetJsonType (JsonType type) {} public JsonType GetJsonType() => JsonType.None;
public void SetLong (long val) {}
public void SetString (string val) {} public Int64 GetLong() => 0L;
public string ToJson () { return ""; } public String GetString() => "";
public void ToJson (JsonWriter writer) {}
public void SetBoolean(Boolean val) { }
bool IList.IsFixedSize { get { return true; } } public void SetDouble(Double val) { }
bool IList.IsReadOnly { get { return true; } }
public void SetInt(Int32 val) { }
object IList.this[int index] {
get { return null; } public void SetJsonType(JsonType type) { }
set {}
} public void SetLong(Int64 val) { }
int IList.Add (object value) { return 0; } public void SetString(String val) { }
void IList.Clear () {}
bool IList.Contains (object value) { return false; } public String ToJson() => "";
int IList.IndexOf (object value) { return -1; }
void IList.Insert (int i, object v) {} public void ToJson(JsonWriter writer) { }
void IList.Remove (object value) {}
void IList.RemoveAt (int index) {} Boolean IList.IsFixedSize => true;
Boolean IList.IsReadOnly => true;
int ICollection.Count { get { return 0; } }
bool ICollection.IsSynchronized { get { return false; } } Object IList.this[Int32 index] {
object ICollection.SyncRoot { get { return null; } } get => null;
set {
void ICollection.CopyTo (Array array, int index) {} }
}
IEnumerator IEnumerable.GetEnumerator () { return null; } Int32 IList.Add(Object value) => 0;
void IList.Clear() { }
bool IDictionary.IsFixedSize { get { return true; } }
bool IDictionary.IsReadOnly { get { return true; } } Boolean IList.Contains(Object value) => false;
ICollection IDictionary.Keys { get { return null; } } Int32 IList.IndexOf(Object value) => -1;
ICollection IDictionary.Values { get { return null; } }
void IList.Insert(Int32 i, Object v) { }
object IDictionary.this[object key] {
get { return null; } void IList.Remove(Object value) { }
set {}
} void IList.RemoveAt(Int32 index) { }
void IDictionary.Add (object k, object v) {} Int32 ICollection.Count => 0;
void IDictionary.Clear () {}
bool IDictionary.Contains (object key) { return false; } Boolean ICollection.IsSynchronized => false;
void IDictionary.Remove (object key) {}
Object ICollection.SyncRoot => null;
IDictionaryEnumerator IDictionary.GetEnumerator () { return null; }
void ICollection.CopyTo(Array array, Int32 index) { }
object IOrderedDictionary.this[int idx] { IEnumerator IEnumerable.GetEnumerator() => null;
get { return null; }
set {} Boolean IDictionary.IsFixedSize => true;
}
Boolean IDictionary.IsReadOnly => true;
IDictionaryEnumerator IOrderedDictionary.GetEnumerator () {
return null; ICollection IDictionary.Keys => null;
}
void IOrderedDictionary.Insert (int i, object k, object v) {} ICollection IDictionary.Values => null;
void IOrderedDictionary.RemoveAt (int i) {}
} Object IDictionary.this[Object key] {
} get => null;
set {
}
}
void IDictionary.Add(Object k, Object v) { }
void IDictionary.Clear() { }
Boolean IDictionary.Contains(Object key) => false;
void IDictionary.Remove(Object key) { }
IDictionaryEnumerator IDictionary.GetEnumerator() => null;
Object IOrderedDictionary.this[Int32 idx] {
get => null;
set {
}
}
IDictionaryEnumerator IOrderedDictionary.GetEnumerator() => null;
void IOrderedDictionary.Insert(Int32 i, Object k, Object v) { }
void IOrderedDictionary.RemoveAt(Int32 i) { }
}
}

View File

@ -16,463 +16,353 @@ using System.IO;
using System.Text; using System.Text;
namespace LitJson namespace LitJson {
{ public enum JsonToken {
public enum JsonToken None,
{ ObjectStart,
None, PropertyName,
ObjectEnd,
ObjectStart, ArrayStart,
PropertyName, ArrayEnd,
ObjectEnd, Int,
Long,
ArrayStart, Double,
ArrayEnd, String,
Boolean,
Int, Null
Long, }
Double,
String, public class JsonReader {
#region Fields
Boolean, private static readonly IDictionary<Int32, IDictionary<Int32, Int32[]>> parse_table;
Null
} private readonly Stack<Int32> automaton_stack;
private Int32 current_input;
private Int32 current_symbol;
public class JsonReader private readonly Lexer lexer;
{ private Boolean parser_in_string;
#region Fields private Boolean parser_return;
private static readonly IDictionary<int, IDictionary<int, int[]>> parse_table; private Boolean read_started;
private TextReader reader;
private Stack<int> automaton_stack; private readonly Boolean reader_is_owned;
private int current_input; #endregion
private int current_symbol;
private bool end_of_json; #region Public Properties
private bool end_of_input; public Boolean AllowComments {
private Lexer lexer; get => this.lexer.AllowComments;
private bool parser_in_string; set => this.lexer.AllowComments = value;
private bool parser_return; }
private bool read_started;
private TextReader reader; public Boolean AllowSingleQuotedStrings {
private bool reader_is_owned; get => this.lexer.AllowSingleQuotedStrings;
private bool skip_non_members; set => this.lexer.AllowSingleQuotedStrings = value;
private object token_value; }
private JsonToken token;
#endregion public Boolean SkipNonMembers { get; set; }
public Boolean EndOfInput { get; private set; }
#region Public Properties
public bool AllowComments { public Boolean EndOfJson { get; private set; }
get { return lexer.AllowComments; }
set { lexer.AllowComments = value; } public JsonToken Token { get; private set; }
}
public Object Value { get; private set; }
public bool AllowSingleQuotedStrings { #endregion
get { return lexer.AllowSingleQuotedStrings; }
set { lexer.AllowSingleQuotedStrings = value; } #region Constructors
} static JsonReader() => parse_table = PopulateParseTable();
public bool SkipNonMembers { public JsonReader(String json_text) : this(new StringReader(json_text), true) { }
get { return skip_non_members; }
set { skip_non_members = value; } public JsonReader(TextReader reader) : this(reader, false) { }
}
private JsonReader(TextReader reader, Boolean owned) {
public bool EndOfInput { if(reader == null) {
get { return end_of_input; } throw new ArgumentNullException("reader");
} }
public bool EndOfJson { this.parser_in_string = false;
get { return end_of_json; } this.parser_return = false;
}
this.read_started = false;
public JsonToken Token { this.automaton_stack = new Stack<Int32>();
get { return token; } this.automaton_stack.Push((Int32)ParserToken.End);
} this.automaton_stack.Push((Int32)ParserToken.Text);
public object Value { this.lexer = new Lexer(reader);
get { return token_value; }
} this.EndOfInput = false;
#endregion this.EndOfJson = false;
this.SkipNonMembers = true;
#region Constructors
static JsonReader () this.reader = reader;
{ this.reader_is_owned = owned;
parse_table = PopulateParseTable (); }
} #endregion
public JsonReader (string json_text) : #region Static Methods
this (new StringReader (json_text), true) private static IDictionary<Int32, IDictionary<Int32, Int32[]>> PopulateParseTable() =>
{ // See section A.2. of the manual for details
} new Dictionary<Int32, IDictionary<Int32, Int32[]>> {
{
public JsonReader (TextReader reader) : (Int32)ParserToken.Array,
this (reader, false) new Dictionary<Int32, Int32[]> {
{ { '[', new Int32[] { '[', (Int32)ParserToken.ArrayPrime } }
} }
},
private JsonReader (TextReader reader, bool owned) {
{ (Int32)ParserToken.ArrayPrime,
if (reader == null) new Dictionary<Int32, Int32[]> {
throw new ArgumentNullException ("reader"); { '"', new Int32[] { (Int32)ParserToken.Value, (Int32)ParserToken.ValueRest, ']' } },
{ '[', new Int32[] { (Int32)ParserToken.Value, (Int32)ParserToken.ValueRest, ']' } },
parser_in_string = false; { ']', new Int32[] { ']' } },
parser_return = false; { '{', new Int32[] { (Int32)ParserToken.Value, (Int32)ParserToken.ValueRest, ']' } },
{ (Int32)ParserToken.Number, new Int32[] { (Int32)ParserToken.Value, (Int32)ParserToken.ValueRest, ']' } },
read_started = false; { (Int32)ParserToken.True, new Int32[] { (Int32)ParserToken.Value, (Int32)ParserToken.ValueRest, ']' } },
automaton_stack = new Stack<int> (); { (Int32)ParserToken.False, new Int32[] { (Int32)ParserToken.Value, (Int32)ParserToken.ValueRest, ']' } },
automaton_stack.Push ((int) ParserToken.End); { (Int32)ParserToken.Null, new Int32[] { (Int32)ParserToken.Value, (Int32)ParserToken.ValueRest, ']' } }
automaton_stack.Push ((int) ParserToken.Text); }
},
lexer = new Lexer (reader); {
(Int32)ParserToken.Object,
end_of_input = false; new Dictionary<Int32, Int32[]> {
end_of_json = false; { '{', new Int32[] { '{', (Int32)ParserToken.ObjectPrime } }
}
skip_non_members = true; },
{
this.reader = reader; (Int32)ParserToken.ObjectPrime,
reader_is_owned = owned; new Dictionary<Int32, Int32[]> {
} { '"', new Int32[] { (Int32)ParserToken.Pair, (Int32)ParserToken.PairRest, '}' } },
#endregion { '}', new Int32[] { '}' } }
}
},
#region Static Methods {
private static IDictionary<int, IDictionary<int, int[]>> PopulateParseTable () (Int32)ParserToken.Pair,
{ new Dictionary<Int32, Int32[]> {
// See section A.2. of the manual for details { '"', new Int32[] { (Int32)ParserToken.String, ':', (Int32)ParserToken.Value } }
IDictionary<int, IDictionary<int, int[]>> parse_table = new Dictionary<int, IDictionary<int, int[]>> (); }
},
TableAddRow (parse_table, ParserToken.Array); {
TableAddCol (parse_table, ParserToken.Array, '[', (Int32)ParserToken.PairRest,
'[', new Dictionary<Int32, Int32[]> {
(int) ParserToken.ArrayPrime); { ',', new Int32[] { ',', (Int32)ParserToken.Pair, (Int32)ParserToken.PairRest } },
{ '}', new Int32[] { (Int32)ParserToken.Epsilon } }
TableAddRow (parse_table, ParserToken.ArrayPrime); }
TableAddCol (parse_table, ParserToken.ArrayPrime, '"', },
(int) ParserToken.Value, {
(Int32)ParserToken.String,
(int) ParserToken.ValueRest, new Dictionary<Int32, Int32[]> {
']'); { '"', new Int32[] { '"', (Int32)ParserToken.CharSeq, '"' } }
TableAddCol (parse_table, ParserToken.ArrayPrime, '[', }
(int) ParserToken.Value, },
(int) ParserToken.ValueRest, {
']'); (Int32)ParserToken.Text,
TableAddCol (parse_table, ParserToken.ArrayPrime, ']', new Dictionary<Int32, Int32[]> {
']'); { '[', new Int32[] { (Int32)ParserToken.Array } },
TableAddCol (parse_table, ParserToken.ArrayPrime, '{', { '{', new Int32[] { (Int32)ParserToken.Object } }
(int) ParserToken.Value, }
(int) ParserToken.ValueRest, },
']'); {
TableAddCol (parse_table, ParserToken.ArrayPrime, (int) ParserToken.Number, (Int32)ParserToken.Value,
(int) ParserToken.Value, new Dictionary<Int32, Int32[]> {
(int) ParserToken.ValueRest, { '"', new Int32[] { (Int32)ParserToken.String } },
']'); { '[', new Int32[] { (Int32)ParserToken.Array } },
TableAddCol (parse_table, ParserToken.ArrayPrime, (int) ParserToken.True, { '{', new Int32[] { (Int32)ParserToken.Object } },
(int) ParserToken.Value, { (Int32)ParserToken.Number, new Int32[] { (Int32)ParserToken.Number } },
(int) ParserToken.ValueRest, { (Int32)ParserToken.True, new Int32[] { (Int32)ParserToken.True } },
']'); { (Int32)ParserToken.False, new Int32[] { (Int32)ParserToken.False } },
TableAddCol (parse_table, ParserToken.ArrayPrime, (int) ParserToken.False, { (Int32)ParserToken.Null, new Int32[] { (Int32)ParserToken.Null } }
(int) ParserToken.Value, }
(int) ParserToken.ValueRest, },
']'); {
TableAddCol (parse_table, ParserToken.ArrayPrime, (int) ParserToken.Null, (Int32)ParserToken.ValueRest,
(int) ParserToken.Value, new Dictionary<Int32, Int32[]> {
(int) ParserToken.ValueRest, { ',', new Int32[] { ',', (Int32)ParserToken.Value, (Int32)ParserToken.ValueRest } },
']'); { ']', new Int32[] { (Int32)ParserToken.Epsilon } }
}
TableAddRow (parse_table, ParserToken.Object); }
TableAddCol (parse_table, ParserToken.Object, '{', };
'{', #endregion
(int) ParserToken.ObjectPrime);
#region Private Methods
TableAddRow (parse_table, ParserToken.ObjectPrime); private void ProcessNumber(String number) {
TableAddCol (parse_table, ParserToken.ObjectPrime, '"', if(number.IndexOf('.') != -1 || number.IndexOf('e') != -1 || number.IndexOf('E') != -1) {
(int) ParserToken.Pair, if(Double.TryParse(number, NumberStyles.Any, CultureInfo.InvariantCulture, out Double n_double)) {
(int) ParserToken.PairRest, this.Token = JsonToken.Double;
'}'); this.Value = n_double;
TableAddCol (parse_table, ParserToken.ObjectPrime, '}', return;
'}'); }
}
TableAddRow (parse_table, ParserToken.Pair);
TableAddCol (parse_table, ParserToken.Pair, '"', if(Int32.TryParse(number, NumberStyles.Integer, CultureInfo.InvariantCulture, out Int32 n_int32)) {
(int) ParserToken.String, this.Token = JsonToken.Int;
':', this.Value = n_int32;
(int) ParserToken.Value); return;
}
TableAddRow (parse_table, ParserToken.PairRest);
TableAddCol (parse_table, ParserToken.PairRest, ',', if(Int64.TryParse(number, NumberStyles.Integer, CultureInfo.InvariantCulture, out Int64 n_int64)) {
',', this.Token = JsonToken.Long;
(int) ParserToken.Pair, this.Value = n_int64;
(int) ParserToken.PairRest); return;
TableAddCol (parse_table, ParserToken.PairRest, '}', }
(int) ParserToken.Epsilon);
if(UInt64.TryParse(number, NumberStyles.Integer, CultureInfo.InvariantCulture, out UInt64 n_uint64)) {
TableAddRow (parse_table, ParserToken.String); this.Token = JsonToken.Long;
TableAddCol (parse_table, ParserToken.String, '"', this.Value = n_uint64;
'"', return;
(int) ParserToken.CharSeq, }
'"');
// Shouldn't happen, but just in case, return something
TableAddRow (parse_table, ParserToken.Text); this.Token = JsonToken.Int;
TableAddCol (parse_table, ParserToken.Text, '[', this.Value = 0;
(int) ParserToken.Array); }
TableAddCol (parse_table, ParserToken.Text, '{',
(int) ParserToken.Object); private void ProcessSymbol() {
if(this.current_symbol == '[') {
TableAddRow (parse_table, ParserToken.Value); this.Token = JsonToken.ArrayStart;
TableAddCol (parse_table, ParserToken.Value, '"', this.parser_return = true;
(int) ParserToken.String); } else if(this.current_symbol == ']') {
TableAddCol (parse_table, ParserToken.Value, '[', this.Token = JsonToken.ArrayEnd;
(int) ParserToken.Array); this.parser_return = true;
TableAddCol (parse_table, ParserToken.Value, '{', } else if(this.current_symbol == '{') {
(int) ParserToken.Object); this.Token = JsonToken.ObjectStart;
TableAddCol (parse_table, ParserToken.Value, (int) ParserToken.Number, this.parser_return = true;
(int) ParserToken.Number); } else if(this.current_symbol == '}') {
TableAddCol (parse_table, ParserToken.Value, (int) ParserToken.True, this.Token = JsonToken.ObjectEnd;
(int) ParserToken.True); this.parser_return = true;
TableAddCol (parse_table, ParserToken.Value, (int) ParserToken.False, } else if(this.current_symbol == '"') {
(int) ParserToken.False); if(this.parser_in_string) {
TableAddCol (parse_table, ParserToken.Value, (int) ParserToken.Null, this.parser_in_string = false;
(int) ParserToken.Null); this.parser_return = true;
} else {
TableAddRow (parse_table, ParserToken.ValueRest); if(this.Token == JsonToken.None) {
TableAddCol (parse_table, ParserToken.ValueRest, ',', this.Token = JsonToken.String;
',', }
(int) ParserToken.Value, this.parser_in_string = true;
(int) ParserToken.ValueRest); }
TableAddCol (parse_table, ParserToken.ValueRest, ']', } else if(this.current_symbol == (Int32)ParserToken.CharSeq) {
(int) ParserToken.Epsilon); this.Value = this.lexer.StringValue;
} else if(this.current_symbol == (Int32)ParserToken.False) {
return parse_table; this.Token = JsonToken.Boolean;
} this.Value = false;
this.parser_return = true;
private static void TableAddCol (IDictionary<int, IDictionary<int, int[]>> parse_table, ParserToken row, int col, } else if(this.current_symbol == (Int32)ParserToken.Null) {
params int[] symbols) this.Token = JsonToken.Null;
{ this.parser_return = true;
parse_table[(int) row].Add (col, symbols); } else if(this.current_symbol == (Int32)ParserToken.Number) {
} this.ProcessNumber(this.lexer.StringValue);
this.parser_return = true;
private static void TableAddRow (IDictionary<int, IDictionary<int, int[]>> parse_table, ParserToken rule) } else if(this.current_symbol == (Int32)ParserToken.Pair) {
{ this.Token = JsonToken.PropertyName;
parse_table.Add ((int) rule, new Dictionary<int, int[]> ()); } else if(this.current_symbol == (Int32)ParserToken.True) {
} this.Token = JsonToken.Boolean;
#endregion this.Value = true;
this.parser_return = true;
}
#region Private Methods }
private void ProcessNumber (string number)
{ private Boolean ReadToken() {
if (number.IndexOf ('.') != -1 || if(this.EndOfInput) {
number.IndexOf ('e') != -1 || return false;
number.IndexOf ('E') != -1) { }
_ = this.lexer.NextToken();
double n_double; if(this.lexer.EndOfInput) {
if (double.TryParse (number, NumberStyles.Any, CultureInfo.InvariantCulture, out n_double)) { this.Close();
token = JsonToken.Double; return false;
token_value = n_double; }
this.current_input = this.lexer.Token;
return; return true;
} }
} #endregion
int n_int32;
if (int.TryParse (number, NumberStyles.Integer, CultureInfo.InvariantCulture, out n_int32)) { public void Close() {
token = JsonToken.Int; if(this.EndOfInput) {
token_value = n_int32; return;
}
return; this.EndOfInput = true;
} this.EndOfJson = true;
if(this.reader_is_owned) {
long n_int64; using(this.reader) {
if (long.TryParse (number, NumberStyles.Integer, CultureInfo.InvariantCulture, out n_int64)) { }
token = JsonToken.Long; }
token_value = n_int64; this.reader = null;
}
return;
} public Boolean Read() {
if(this.EndOfInput) {
ulong n_uint64; return false;
if (ulong.TryParse(number, NumberStyles.Integer, CultureInfo.InvariantCulture, out n_uint64)) }
{ if(this.EndOfJson) {
token = JsonToken.Long; this.EndOfJson = false;
token_value = n_uint64; this.automaton_stack.Clear();
this.automaton_stack.Push((Int32)ParserToken.End);
return; this.automaton_stack.Push((Int32)ParserToken.Text);
} }
this.parser_in_string = false;
// Shouldn't happen, but just in case, return something this.parser_return = false;
token = JsonToken.Int; this.Token = JsonToken.None;
token_value = 0; this.Value = null;
} if(!this.read_started) {
this.read_started = true;
private void ProcessSymbol () if(!this.ReadToken()) {
{ return false;
if (current_symbol == '[') { }
token = JsonToken.ArrayStart; }
parser_return = true;
} else if (current_symbol == ']') { Int32[] entry_symbols;
token = JsonToken.ArrayEnd;
parser_return = true; while(true) {
if(this.parser_return) {
} else if (current_symbol == '{') { if(this.automaton_stack.Peek() == (Int32)ParserToken.End) {
token = JsonToken.ObjectStart; this.EndOfJson = true;
parser_return = true; }
} else if (current_symbol == '}') { return true;
token = JsonToken.ObjectEnd; }
parser_return = true;
this.current_symbol = this.automaton_stack.Pop();
} else if (current_symbol == '"') {
if (parser_in_string) { this.ProcessSymbol();
parser_in_string = false;
if(this.current_symbol == this.current_input) {
parser_return = true; if(!this.ReadToken()) {
if(this.automaton_stack.Peek() != (Int32)ParserToken.End) {
} else { throw new JsonException(
if (token == JsonToken.None) "Input doesn't evaluate to proper JSON text");
token = JsonToken.String; }
parser_in_string = true; if(this.parser_return) {
} return true;
}
} else if (current_symbol == (int) ParserToken.CharSeq) {
token_value = lexer.StringValue; return false;
}
} else if (current_symbol == (int) ParserToken.False) {
token = JsonToken.Boolean; continue;
token_value = false; }
parser_return = true;
try {
} else if (current_symbol == (int) ParserToken.Null) {
token = JsonToken.Null; entry_symbols =
parser_return = true; parse_table[this.current_symbol][this.current_input];
} else if (current_symbol == (int) ParserToken.Number) { } catch(KeyNotFoundException e) {
ProcessNumber (lexer.StringValue); throw new JsonException((ParserToken)this.current_input, e);
}
parser_return = true;
if(entry_symbols[0] == (Int32)ParserToken.Epsilon) {
} else if (current_symbol == (int) ParserToken.Pair) { continue;
token = JsonToken.PropertyName; }
} else if (current_symbol == (int) ParserToken.True) { for(Int32 i = entry_symbols.Length - 1; i >= 0; i--) {
token = JsonToken.Boolean; this.automaton_stack.Push(entry_symbols[i]);
token_value = true; }
parser_return = true; }
}
}
} }
private bool ReadToken ()
{
if (end_of_input)
return false;
lexer.NextToken ();
if (lexer.EndOfInput) {
Close ();
return false;
}
current_input = lexer.Token;
return true;
}
#endregion
public void Close ()
{
if (end_of_input)
return;
end_of_input = true;
end_of_json = true;
if (reader_is_owned)
{
using(reader){}
}
reader = null;
}
public bool Read ()
{
if (end_of_input)
return false;
if (end_of_json) {
end_of_json = false;
automaton_stack.Clear ();
automaton_stack.Push ((int) ParserToken.End);
automaton_stack.Push ((int) ParserToken.Text);
}
parser_in_string = false;
parser_return = false;
token = JsonToken.None;
token_value = null;
if (! read_started) {
read_started = true;
if (! ReadToken ())
return false;
}
int[] entry_symbols;
while (true) {
if (parser_return) {
if (automaton_stack.Peek () == (int) ParserToken.End)
end_of_json = true;
return true;
}
current_symbol = automaton_stack.Pop ();
ProcessSymbol ();
if (current_symbol == current_input) {
if (! ReadToken ()) {
if (automaton_stack.Peek () != (int) ParserToken.End)
throw new JsonException (
"Input doesn't evaluate to proper JSON text");
if (parser_return)
return true;
return false;
}
continue;
}
try {
entry_symbols =
parse_table[current_symbol][current_input];
} catch (KeyNotFoundException e) {
throw new JsonException ((ParserToken) current_input, e);
}
if (entry_symbols[0] == (int) ParserToken.Epsilon)
continue;
for (int i = entry_symbols.Length - 1; i >= 0; i--)
automaton_stack.Push (entry_symbols[i]);
}
}
}
} }

View File

@ -1,43 +1,41 @@
#region Header #region Header
/** /**
* JsonWriter.cs * JsonWriter.cs
* Stream-like facility to output JSON text. * Stream-like facility to output JSON text.
* *
* The authors disclaim copyright to this source code. For more details, see * The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution. * the COPYING file included with this distribution.
**/ **/
#endregion #endregion
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.IO; using System.IO;
using System.Text; using System.Text;
namespace LitJson namespace LitJson
{ {
internal enum Condition internal enum Condition {
{ InArray,
InArray, InObject,
InObject, NotAProperty,
NotAProperty, Property,
Property, Value
Value }
}
internal class WriterContext {
internal class WriterContext public Int32 Count;
{ public Boolean InArray;
public Int32 Count; public Boolean InObject;
public Boolean InArray; public Boolean ExpectingValue;
public Boolean InObject; public Int32 Padding;
public Boolean ExpectingValue; }
public Int32 Padding;
}
public class JsonWriter { public class JsonWriter {
#region Fields #region Fields
private static readonly NumberFormatInfo number_format; private static readonly NumberFormatInfo number_format;
private WriterContext context; private WriterContext context;
@ -46,121 +44,90 @@ namespace LitJson
private Char[] hex_seq; private Char[] hex_seq;
private Int32 indentation; private Int32 indentation;
private Int32 indent_value; private Int32 indent_value;
private StringBuilder inst_string_builder; private readonly StringBuilder inst_string_builder;
private Boolean pretty_print; #endregion
private Boolean validate;
private Boolean lower_case_properties;
private TextWriter writer;
#endregion
#region Properties
#region Properties
public Int32 IndentValue { public Int32 IndentValue {
get { return this.indent_value; } get => this.indent_value;
set { set {
this.indentation = (this.indentation / this.indent_value) * value; this.indentation = this.indentation / this.indent_value * value;
this.indent_value = value; this.indent_value = value;
} }
} }
public Boolean PrettyPrint { public Boolean PrettyPrint { get; set; }
get { return this.pretty_print; }
set { this.pretty_print = value; }
}
public TextWriter TextWriter { private TextWriter TextWriter { get; }
get { return this.writer; }
}
public Boolean Validate { public Boolean Validate { get; set; }
get { return this.validate; }
set { this.validate = value; }
}
public Boolean LowerCaseProperties { public Boolean LowerCaseProperties { get; set; }
get { return this.lower_case_properties; } #endregion
set { this.lower_case_properties = value; }
}
#endregion
#region Constructors
#region Constructors static JsonWriter() => number_format = NumberFormatInfo.InvariantInfo;
static JsonWriter() {
number_format = NumberFormatInfo.InvariantInfo;
}
public JsonWriter() { public JsonWriter() {
this.inst_string_builder = new StringBuilder(); this.inst_string_builder = new StringBuilder();
this.writer = new StringWriter(this.inst_string_builder); this.TextWriter = new StringWriter(this.inst_string_builder);
this.Init();
Init();
} }
public JsonWriter(StringBuilder sb) : public JsonWriter(StringBuilder sb) : this(new StringWriter(sb)) { }
this(new StringWriter(sb)) {
}
public JsonWriter(TextWriter writer) { public JsonWriter(TextWriter writer) {
this.writer = writer ?? throw new ArgumentNullException("writer"); this.TextWriter = writer ?? throw new ArgumentNullException("writer");
this.Init();
Init();
} }
#endregion #endregion
#region Private Methods
#region Private Methods
private void DoValidation(Condition cond) { private void DoValidation(Condition cond) {
if (!this.context.ExpectingValue) { if (!this.context.ExpectingValue) {
this.context.Count++; this.context.Count++;
} }
if (!this.validate) { if (!this.Validate) {
return; return;
} }
if (this.has_reached_end) { if (this.has_reached_end) {
throw new JsonException( throw new JsonException("A complete JSON symbol has already been written");
"A complete JSON symbol has already been written");
} }
switch (cond) { switch (cond) {
case Condition.InArray: case Condition.InArray:
if (!this.context.InArray) { if (!this.context.InArray) {
throw new JsonException( throw new JsonException("Can't close an array here");
"Can't close an array here");
} }
break; break;
case Condition.InObject: case Condition.InObject:
if (!this.context.InObject || this.context.ExpectingValue) { if (!this.context.InObject || this.context.ExpectingValue) {
throw new JsonException( throw new JsonException("Can't close an object here");
"Can't close an object here");
} }
break; break;
case Condition.NotAProperty: case Condition.NotAProperty:
if (this.context.InObject && !this.context.ExpectingValue) { if (this.context.InObject && !this.context.ExpectingValue) {
throw new JsonException( throw new JsonException("Expected a property");
"Expected a property");
} }
break; break;
case Condition.Property: case Condition.Property:
if (!this.context.InObject || this.context.ExpectingValue) { if (!this.context.InObject || this.context.ExpectingValue) {
throw new JsonException( throw new JsonException("Can't add a property here");
"Can't add a property here");
} }
break; break;
case Condition.Value: case Condition.Value:
if (!this.context.InArray && if (!this.context.InArray && (!this.context.InObject || !this.context.ExpectingValue)) {
(!this.context.InObject || !this.context.ExpectingValue)) { throw new JsonException("Can't add a value here");
throw new JsonException(
"Can't add a value here");
} }
break; break;
@ -172,9 +139,9 @@ namespace LitJson
this.hex_seq = new Char[4]; this.hex_seq = new Char[4];
this.indentation = 0; this.indentation = 0;
this.indent_value = 4; this.indent_value = 4;
this.pretty_print = false; this.PrettyPrint = false;
this.validate = true; this.Validate = true;
this.lower_case_properties = false; this.LowerCaseProperties = false;
this.ctx_stack = new Stack<WriterContext>(); this.ctx_stack = new Stack<WriterContext>();
this.context = new WriterContext(); this.context = new WriterContext();
@ -183,114 +150,96 @@ namespace LitJson
private static void IntToHex(Int32 n, Char[] hex) { private static void IntToHex(Int32 n, Char[] hex) {
Int32 num; Int32 num;
for (Int32 i = 0; i < 4; i++) { for (Int32 i = 0; i < 4; i++) {
num = n % 16; num = n % 16;
hex[3 - i] = num < 10 ? (Char)('0' + num) : (Char)('A' + (num - 10));
if (num < 10) {
hex[3 - i] = (Char)('0' + num);
} else {
hex[3 - i] = (Char)('A' + (num - 10));
}
n >>= 4; n >>= 4;
} }
} }
private void Indent() { private void Indent() {
if (this.pretty_print) { if (this.PrettyPrint) {
this.indentation += this.indent_value; this.indentation += this.indent_value;
} }
} }
private void Put(String str) { private void Put(String str) {
if (this.pretty_print && !this.context.ExpectingValue) { if (this.PrettyPrint && !this.context.ExpectingValue) {
for (Int32 i = 0; i < this.indentation; i++) { for (Int32 i = 0; i < this.indentation; i++) {
this.writer.Write(' '); this.TextWriter.Write(' ');
} }
} }
this.TextWriter.Write(str);
this.writer.Write(str);
} }
private void PutNewline() { private void PutNewline() => this.PutNewline(true);
PutNewline(true);
}
private void PutNewline(Boolean add_comma) { private void PutNewline(Boolean add_comma) {
if (add_comma && !this.context.ExpectingValue && if (add_comma && !this.context.ExpectingValue && this.context.Count > 1) {
this.context.Count > 1) { this.TextWriter.Write(',');
this.writer.Write(',');
} }
if (this.PrettyPrint && !this.context.ExpectingValue) {
if (this.pretty_print && !this.context.ExpectingValue) { this.TextWriter.Write(Environment.NewLine);
this.writer.Write(Environment.NewLine);
} }
} }
private void PutString(String str) { private void PutString(String str) {
Put(String.Empty); this.Put(String.Empty);
this.writer.Write('"'); this.TextWriter.Write('"');
Int32 n = str.Length; Int32 n = str.Length;
for (Int32 i = 0; i < n; i++) { for (Int32 i = 0; i < n; i++) {
switch (str[i]) { switch (str[i]) {
case '\n': case '\n':
this.writer.Write("\\n"); this.TextWriter.Write("\\n");
continue; continue;
case '\r': case '\r':
this.writer.Write("\\r"); this.TextWriter.Write("\\r");
continue; continue;
case '\t': case '\t':
this.writer.Write("\\t"); this.TextWriter.Write("\\t");
continue; continue;
case '"': case '"':
case '\\': case '\\':
this.writer.Write('\\'); this.TextWriter.Write('\\');
this.writer.Write(str[i]); this.TextWriter.Write(str[i]);
continue; continue;
case '\f': case '\f':
this.writer.Write("\\f"); this.TextWriter.Write("\\f");
continue; continue;
case '\b': case '\b':
this.writer.Write("\\b"); this.TextWriter.Write("\\b");
continue; continue;
} }
if (str[i] >= 32 && str[i] <= 126) { if (str[i] >= 32 && str[i] <= 126) {
this.writer.Write(str[i]); this.TextWriter.Write(str[i]);
continue; continue;
} }
// Default, turn into a \uXXXX sequence // Default, turn into a \uXXXX sequence
IntToHex(str[i], this.hex_seq); IntToHex(str[i], this.hex_seq);
this.writer.Write("\\u"); this.TextWriter.Write("\\u");
this.writer.Write(this.hex_seq); this.TextWriter.Write(this.hex_seq);
} }
this.writer.Write('"'); this.TextWriter.Write('"');
} }
private void Unindent() { private void Unindent() {
if (this.pretty_print) { if (this.PrettyPrint) {
this.indentation -= this.indent_value; this.indentation -= this.indent_value;
} }
} }
#endregion #endregion
public override String ToString() => this.inst_string_builder == null ? String.Empty : this.inst_string_builder.ToString();
public override String ToString() {
if (this.inst_string_builder == null) {
return String.Empty;
}
return this.inst_string_builder.ToString();
}
public void Reset() { public void Reset() {
this.has_reached_end = false; this.has_reached_end = false;
@ -300,88 +249,100 @@ namespace LitJson
this.ctx_stack.Push(this.context); this.ctx_stack.Push(this.context);
if (this.inst_string_builder != null) { if (this.inst_string_builder != null) {
this.inst_string_builder.Remove(0, this.inst_string_builder.Length); _ = this.inst_string_builder.Remove(0, this.inst_string_builder.Length);
} }
} }
public void Write(Boolean boolean) { public void Write(Boolean boolean) {
DoValidation(Condition.Value); this.DoValidation(Condition.Value);
PutNewline(); this.PutNewline();
Put(boolean ? "true" : "false"); this.Put(boolean ? "true" : "false");
this.context.ExpectingValue = false; this.context.ExpectingValue = false;
} }
public void Write(Decimal number) { public void Write(Decimal number) {
DoValidation(Condition.Value); this.DoValidation(Condition.Value);
PutNewline(); this.PutNewline();
Put(Convert.ToString(number, number_format)); this.Put(Convert.ToString(number, number_format));
this.context.ExpectingValue = false; this.context.ExpectingValue = false;
} }
public void Write(Double number) { public void Write(Double number) {
DoValidation(Condition.Value); this.DoValidation(Condition.Value);
PutNewline(); this.PutNewline();
String str = Convert.ToString(number, number_format); String str = Convert.ToString(number, number_format);
Put(str); this.Put(str);
if (str.IndexOf('.') == -1 && str.IndexOf('E') == -1) { if (str.IndexOf('.') == -1 && str.IndexOf('E') == -1) {
this.writer.Write(".0"); this.TextWriter.Write(".0");
} }
this.context.ExpectingValue = false; this.context.ExpectingValue = false;
} }
public void Write(Int32 number) { public void Write(Int32 number) {
DoValidation(Condition.Value); this.DoValidation(Condition.Value);
PutNewline(); this.PutNewline();
Put(Convert.ToString(number, number_format)); this.Put(Convert.ToString(number, number_format));
this.context.ExpectingValue = false; this.context.ExpectingValue = false;
} }
public void Write(Int64 number) { public void Write(Int64 number) {
DoValidation(Condition.Value); this.DoValidation(Condition.Value);
PutNewline(); this.PutNewline();
Put(Convert.ToString(number, number_format)); this.Put(Convert.ToString(number, number_format));
this.context.ExpectingValue = false; this.context.ExpectingValue = false;
} }
public void Write(String str) { public void Write(String str) {
DoValidation(Condition.Value); this.DoValidation(Condition.Value);
PutNewline(); this.PutNewline();
if (str == null) { if (str == null) {
Put("null"); this.Put("null");
} else { } else {
PutString(str); this.PutString(str);
} }
this.context.ExpectingValue = false; this.context.ExpectingValue = false;
} }
// [CLSCompliant(false)] public void WriteJson(String str) {
public void Write(UInt64 number) { this.DoValidation(Condition.Value);
DoValidation(Condition.Value); this.PutNewline();
PutNewline();
Put(Convert.ToString(number, number_format)); if(str == null) {
this.Put("null");
} else {
this.TextWriter.Write(str);
}
this.context.ExpectingValue = false;
}
public void Write(UInt64 number) {
this.DoValidation(Condition.Value);
this.PutNewline();
this.Put(Convert.ToString(number, number_format));
this.context.ExpectingValue = false; this.context.ExpectingValue = false;
} }
public void WriteArrayEnd() { public void WriteArrayEnd() {
DoValidation(Condition.InArray); this.DoValidation(Condition.InArray);
PutNewline(false); this.PutNewline(false);
this.ctx_stack.Pop(); _ = this.ctx_stack.Pop();
if (this.ctx_stack.Count == 1) { if (this.ctx_stack.Count == 1) {
this.has_reached_end = true; this.has_reached_end = true;
} else { } else {
@ -389,29 +350,29 @@ namespace LitJson
this.context.ExpectingValue = false; this.context.ExpectingValue = false;
} }
Unindent(); this.Unindent();
Put("]"); this.Put("]");
} }
public void WriteArrayStart() { public void WriteArrayStart() {
DoValidation(Condition.NotAProperty); this.DoValidation(Condition.NotAProperty);
PutNewline(); this.PutNewline();
Put("["); this.Put("[");
this.context = new WriterContext { this.context = new WriterContext {
InArray = true InArray = true
}; };
this.ctx_stack.Push(this.context); this.ctx_stack.Push(this.context);
Indent(); this.Indent();
} }
public void WriteObjectEnd() { public void WriteObjectEnd() {
DoValidation(Condition.InObject); this.DoValidation(Condition.InObject);
PutNewline(false); this.PutNewline(false);
this.ctx_stack.Pop(); _ = this.ctx_stack.Pop();
if (this.ctx_stack.Count == 1) { if (this.ctx_stack.Count == 1) {
this.has_reached_end = true; this.has_reached_end = true;
} else { } else {
@ -419,47 +380,47 @@ namespace LitJson
this.context.ExpectingValue = false; this.context.ExpectingValue = false;
} }
Unindent(); this.Unindent();
Put("}"); this.Put("}");
} }
public void WriteObjectStart() { public void WriteObjectStart() {
DoValidation(Condition.NotAProperty); this.DoValidation(Condition.NotAProperty);
PutNewline(); this.PutNewline();
Put("{"); this.Put("{");
this.context = new WriterContext { this.context = new WriterContext {
InObject = true InObject = true
}; };
this.ctx_stack.Push(this.context); this.ctx_stack.Push(this.context);
Indent(); this.Indent();
} }
public void WritePropertyName(String property_name) { public void WritePropertyName(String property_name) {
DoValidation(Condition.Property); this.DoValidation(Condition.Property);
PutNewline(); this.PutNewline();
String propertyName = (property_name == null || !this.lower_case_properties) ? property_name : property_name.ToLowerInvariant(); String propertyName = (property_name == null || !this.LowerCaseProperties) ? property_name : property_name.ToLowerInvariant();
PutString(propertyName); this.PutString(propertyName);
if (this.pretty_print) { if (this.PrettyPrint) {
if (propertyName.Length > this.context.Padding) { if (propertyName.Length > this.context.Padding) {
this.context.Padding = propertyName.Length; this.context.Padding = propertyName.Length;
} }
for (Int32 i = this.context.Padding - propertyName.Length; for (Int32 i = this.context.Padding - propertyName.Length;
i >= 0; i--) { i >= 0; i--) {
this.writer.Write(' '); this.TextWriter.Write(' ');
} }
this.writer.Write(": "); this.TextWriter.Write(": ");
} else { } else {
this.writer.Write(':'); this.TextWriter.Write(':');
} }
this.context.ExpectingValue = true; this.context.ExpectingValue = true;
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -9,36 +9,34 @@
#endregion #endregion
namespace LitJson namespace LitJson {
{ internal enum ParserToken {
internal enum ParserToken // Lexer tokens (see section A.1.1. of the manual)
{ None = System.Char.MaxValue + 1,
// Lexer tokens (see section A.1.1. of the manual) Number,
None = System.Char.MaxValue + 1, True,
Number, False,
True, Null,
False, CharSeq,
Null, // Single char
CharSeq, Char,
// Single char
Char, // Parser Rules (see section A.2.1 of the manual)
Text,
// Parser Rules (see section A.2.1 of the manual) Object,
Text, ObjectPrime,
Object, Pair,
ObjectPrime, PairRest,
Pair, Array,
PairRest, ArrayPrime,
Array, Value,
ArrayPrime, ValueRest,
Value, String,
ValueRest,
String, // End of input
End,
// End of input
End, // The empty rule
Epsilon
// The empty rule }
Epsilon
}
} }

View File

@ -1,4 +1,5 @@
using System.Reflection; #if !NETCOREAPP
using System.Reflection;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
@ -34,3 +35,4 @@ using System.Runtime.InteropServices;
// [assembly: AssemblyVersion("1.0.*")] // [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.12.0")] [assembly: AssemblyVersion("0.12.0")]
[assembly: AssemblyFileVersion("0.12.0")] [assembly: AssemblyFileVersion("0.12.0")]
#endif

33
litjson/litjson.csproj Normal file
View File

@ -0,0 +1,33 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AssemblyName>LitJson</AssemblyName>
<RootNamespace>litjson</RootNamespace>
<PackageId>LitJson</PackageId>
<Product>LitJSON</Product>
<Description>LitJSON library</Description>
<Company />
<Authors />
<Version>0.12.0</Version>
<AssemblyVersion>0.12.0</AssemblyVersion>
<FileVersion>0.12.0</FileVersion>
<PackageLicenseFile>COPYING</PackageLicenseFile>
<Copyright>The authors disclaim copyright to this source code</Copyright>
</PropertyGroup>
<ItemGroup>
<Content Include="../COPYING" />
<Content Include="../README.md" />
</ItemGroup>
<ItemGroup>
<None Include="..\COPYING">
<Pack>True</Pack>
<PackagePath></PackagePath>
</None>
</ItemGroup>
</Project>

View File

@ -21,6 +21,7 @@
<DefineConstants>DEBUG;TRACE</DefineConstants> <DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<LangVersion>7.1</LangVersion>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType> <DebugType>pdbonly</DebugType>
@ -29,6 +30,7 @@
<DefineConstants>TRACE</DefineConstants> <DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<LangVersion>7.1</LangVersion>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System" /> <Reference Include="System" />
@ -53,5 +55,9 @@
<Compile Include="ParserToken.cs" /> <Compile Include="ParserToken.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Content Include="..\COPYING" />
<Content Include="..\README.md" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project> </Project>