Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for all C# primitives. #36

Merged
merged 1 commit into from
Jul 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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());
}
}
}