Skip to content

Commit

Permalink
Merge pull request #36 from big-run-studios/bugfix/primitives
Browse files Browse the repository at this point in the history
Added support for all C# primitives.
  • Loading branch information
zanders3 authored Jul 15, 2020
2 parents a8e2c11 + c38c0de commit 01c586d
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 3 deletions.
18 changes: 15 additions & 3 deletions src/JSONWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@ static void AppendValue(StringBuilder stringBuilder, object item)
}

Type type = item.GetType();
if (type == typeof(string))
if (type == typeof(string) || type == typeof(char))
{
stringBuilder.Append('"');
string str = (string)item;
string str = item.ToString();
for (int i = 0; i<str.Length; ++i)
if (str[i] < ' ' || str[i] == '"' || str[i] == '\\')
{
Expand All @@ -47,7 +47,19 @@ static void AppendValue(StringBuilder stringBuilder, object item)
stringBuilder.Append(str[i]);
stringBuilder.Append('"');
}
else if (type == typeof(byte) || type == typeof(int))
else if (type == typeof(byte) || type == typeof(sbyte))
{
stringBuilder.Append(item.ToString());
}
else if (type == typeof(short) || type == typeof(ushort))
{
stringBuilder.Append(item.ToString());
}
else if (type == typeof(int) || type == typeof(uint))
{
stringBuilder.Append(item.ToString());
}
else if (type == typeof(long) || type == typeof(ulong))
{
stringBuilder.Append(item.ToString());
}
Expand Down
40 changes: 40 additions & 0 deletions test/TestWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -155,5 +155,45 @@ public void TestEnumMember()
Assert.AreEqual("{\"Colors\":\"Blue\",\"Style\":\"Underline\"}", new EnumClass { Colors = (Color)2, Style = (Style)4 }.ToJson());
Assert.AreEqual("{\"Colors\":\"10\",\"Style\":\"17\"}", new EnumClass { Colors = (Color)10, Style = (Style)17 }.ToJson());
}

public class PrimitiveObject
{
public bool Bool;
public byte Byte;
public sbyte SByte;
public short Short;
public ushort UShort;
public int Int;
public uint UInt;
public long Long;
public ulong ULong;
public char Char;
public float Single;
public double Double;
public decimal Decimal;
}

[TestMethod]
public void TestPrimitives()
{
Assert.AreEqual(
"{\"Bool\":true,\"Byte\":17,\"SByte\":-17,\"Short\":-123,\"UShort\":123,\"Int\":-56,\"UInt\":56,\"Long\":-34,\"ULong\":34,\"Char\":\"C\",\"Single\":4.3,\"Double\":5.6,\"Decimal\":10.1}",
new PrimitiveObject
{
Bool = true,
Byte = 17,
SByte = -17,
Short = -123,
UShort = 123,
Int = -56,
UInt = 56,
Long = -34,
ULong = 34,
Char = 'C',
Single = 4.3f,
Double = 5.6,
Decimal = 10.1M
}.ToJson());
}
}
}

0 comments on commit 01c586d

Please sign in to comment.