Skip to content

Instantly share code, notes, and snippets.

@robertwahler
Created April 10, 2015 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertwahler/a17cf3a990207212344d to your computer and use it in GitHub Desktop.
Save robertwahler/a17cf3a990207212344d to your computer and use it in GitHub Desktop.
using System;
using FullSerializer;
namespace SDD.Serializers {
public static class JsonSerializer {
/// <summary>
/// Static Serializer Instance
/// </summary>
public static readonly fsSerializer serializer = new fsSerializer();
/// <summary>
/// Serializes the object into json. Will throw exceptions.
/// </summary>
/// <param name="type"></param>
/// <param name="value"></param>
/// <param name="prettyPrint"></param>
/// <returns></returns>
public static string Serialize(Type type, object value, bool prettyPrint = true) {
fsData data;
fsResult result = serializer.TrySerialize(type, value, out data).AssertSuccessWithoutWarnings();
if (result.Failed) {
throw result.AsException;
}
if (prettyPrint) {
return fsJsonPrinter.PrettyJson(data);
}
else {
return fsJsonPrinter.CompressedJson(data);
}
}
/// <summary>
/// Serializes the object into json. Will throw exceptions.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="prettyPrint"></param>
/// <returns></returns>
public static string Serialize<T>(T value, bool prettyPrint = true) {
fsData data;
fsResult result = serializer.TrySerialize<T>(value, out data);
if (result.Failed) {
throw result.AsException;
}
if (prettyPrint) {
return fsJsonPrinter.PrettyJson(data);
}
else {
return fsJsonPrinter.CompressedJson(data);
}
}
/// <summary>
/// Deserializes the Json into an object. Will not throw exceptions.
/// </summary>
/// <param name="type"></param>
/// <param name="json"></param>
/// <returns></returns>
public static object Deserialize(Type type, string json) {
if (string.IsNullOrEmpty(json)) {
return null;
}
// step 1: parse the JSON data
fsData data = fsJsonParser.Parse(json);
// step 2: deserialize the data
object deserialized = null;
serializer.TryDeserialize(data, type, ref deserialized).AssertSuccessWithoutWarnings();
return deserialized;
}
/// <summary>
/// Deserializes the Json into an object. Will throw exceptions.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="json"></param>
/// <returns></returns>
public static T Deserialize<T>(string json) {
if (string.IsNullOrEmpty(json)) {
return default(T);
}
fsData data;
fsResult fsFailure1 = fsJsonParser.Parse(json, out data);
if (fsFailure1.Failed) {
throw fsFailure1.AsException;
}
T instance = default(T);
fsResult fsFailure2 = serializer.TryDeserialize<T>(data, ref instance);
if (fsFailure2.Failed) {
throw fsFailure2.AsException;
}
return instance;
}
/// <summary>
/// Deserializes the Json into an object. Reuses instance reference. Will throw exceptions.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="json"></param>
/// <returns></returns>
public static T Deserialize<T>(string json, ref T instance) {
if (string.IsNullOrEmpty(json)) {
return default(T);
}
fsData data;
fsResult fsFailure1 = fsJsonParser.Parse(json, out data);
if (fsFailure1.Failed) {
throw fsFailure1.AsException;
}
object boxed = instance;
fsResult fsFailure2 = serializer.TryDeserialize(data, typeof(T), ref boxed);
if (fsFailure2.Failed) {
throw fsFailure2.AsException;
}
return (T) boxed;
}
}
}
using UnityEngine;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Linq;
using NUnit.Framework;
using FullSerializer;
using SDD.Serializers;
namespace SDD.Test {
[TestFixture]
[Category("Serializer")]
[Category("JsonSerializerGeneric")]
public class JsonSerializerGenericTest {
[fsObject(MemberSerialization = fsMemberSerialization.OptIn)]
public class TestContents {
[fsProperty]
public int Number { get; set; }
public override string ToString() {
return string.Format("Number={0}", Number);
}
}
[fsObject(MemberSerialization = fsMemberSerialization.OptIn)]
public class TestContainer {
[fsProperty]
public string Id { get; set; }
[fsProperty]
public List<TestContents> Contents { get; set; }
public TestContainer() {
Id = "C1";
Contents = new List<TestContents>();
}
public override string ToString() {
return string.Format("Id={0}, Contents.Count={1}", Id, Contents.Count);
}
}
[SetUp]
public void Before() {
}
[TearDown]
public void After() {
}
[Test]
public void JsonSerializerDoesNotEmitMetadata() {
var container = new TestContainer() { Id = "C7" };
var json = JsonSerializer.Serialize(container, prettyPrint: false);
// {"Id":"C7","Contents":{"$content":[]}}
Debug.Log(json);
Assert.True(Regex.IsMatch(json, @"C7"));
// Fails!!
Assert.False(Regex.IsMatch(json, @"\$content"));
}
[Test]
public void JsonSerializerDeserializeFunctionsWithoutMetadata() {
var json = @"{ ""Id"" : ""C6"", ""Contents"" : [ { ""Number"" : 1}, { ""Number"" : 2} ] }";
var container = JsonSerializer.Deserialize<TestContainer>(json);
Assert.True(container.Id == "C6");
Assert.True(container.Contents.Count == 2);
Assert.True(container.Contents[0].Number == 1);
Assert.True(container.Contents[1].Number == 2);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment