Swifter.Json

Github :

https://github.com/Dogwei/Swifter.Json

The reason why it is powerful, because these features are not in other frameworks!

(1): Supports deep complex object structures and is easy to use.
(2): Use $ref for serialization and deserialization of repeat and circular references.
(3): Currently the only JSON library that supports the ref attribute. 
(4): Support almost all types you use! And allows you to customize the behavior of the type.
(5): Support for .Net Framework 2.0+, .Net Core 2.0+, .Net Standard 2.0+, Mono, Xamarin, Unity.

Swifter.Json utility features

(1): Indented to beautify Json.
(2): Allow 0 or null or "" values ​​to be ignored.
(3): Allows you to customize the behavior of a property or field using the [RWField] property.
(4): Allows you to set the maximum depth to limit the content size.

Types supported by Swifter.Json

bool, byte, sbyte, char, shoft, ushoft, int, uint, long, ulong,
float, double, decimal, string, enum, DateTime, DateTimeOffset,
Guid, TimeSpan, DBNull, Nullable<T>, Version, Type,
Array, Multidimensional-Arrays, IList, IList<T>, ICollection,
ICollection<T>, IDictionary, IDictionary<TKey, TValue>,
IEnumerable, IEnumerable<T>, DataTable, DbDataReader
...
The rest of the types will be treated as Objects, mapped in the form of attribute keys/attribute values.

Is Swifter.Json safe?

I will watch at least one month before each release, during which a lot of testing will be done and the unreleased version will be used in the actual project.
To ensure the stability of the release version. But even then, I can't guarantee that it will be safe. So if you find out
Bug or some unreasonable place, please contact me QQ: 1287905882, email 1287905882@qq.com.

Performance test comparison

The-Net-platform-is-by-far-the-most-powerful-and1

* The color in the chart changes from green to yellow as the time spent. When used more than 3 times, it will be displayed in bright yellow.
	Timeout: Indicates that it took too long.
	Exception: Indicates that an exception has occurred.
	Error: No exception occurred, but the result is incorrect.
* Swifter.Json takes extra time to generate an "action class" (FastObjectRW<T>) for the first execution.
	The follow-up will be faster and faster. So if your program needs to run for a long time, then Swifter.Json is your best choice.
	If your program does not work for this mode, the XObjectRW<T> described below may be for you.

Why is Swifter.Json performance so good?

(1): The best integer and floating point ToString and Parse methods are implemented.
(2): High-performance object mapping tool implemented by Emit.
(3): Local memory allocation! Reject .Net hosted secondary memory.
(4): Use thread caching to keep your program running faster and faster.
(5): Internal full pointer operation, equivalent to using the new .Net Core technology Span<T>!

The version used by other libraries during testing

The-Net-platform-is-by-far-the-most-powerful-and2

How to install Swifter.Json?

Nuget> Install-Package Swifter.Json -Version 1.1.2

Code example

(1): Simple to use

    public class Demo
    {
        public int Id { get; set; }

        public string Name { get; set; }
        
        public static void Main()
        {
            var json = JsonFormatter.SerializeObject(new { Id = 1, Name = "Dogwei" });
            var dictionary = JsonFormatter.DeserializeObject<Dictionary<string, object>>(json);
            var obj = JsonFormatter.DeserializeObject<Demo>(json);
        }
    }

(2): Handling duplicate references

    public class Demo
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public Demo Instance { get; set; }

        public static void Main()
        {
            var jsonFormatter = new JsonFormatter(JsonFormatterOptions.MultiReferencingReference);

            var obj = new Demo() { Id = 1, Name = "Dogwei" };

            obj.Instance = obj;

            var json = jsonFormatter.Serialize(obj);

            var deser = jsonFormatter.Deserialize<Demo>(json);

            Console.WriteLine(json); // {"Id":1,"Instance":{"$ref":"#"},"Name":"Dogwei"}

            Console.WriteLine(deser.Instance == deser); // True
        }
    }

(3): RWField characteristics

    public class Demo
    {
        [RWField("First Name")]
        public string Name { get; set; }

        [RWField]
        public int Age;

        [RWField(Access = RWFieldAccess.Ignore)]
        public int Sex { get; set; }
        [RWField(Order = 1)]
        public int Id { get; set; }

        public static void Main()
        {
            var obj = new Demo() { Id = 1, Name = "Dogwei", Age = 22, Sex = 1 };

            var json = JsonFormatter.SerializeObject(obj);

            Console.WriteLine(json); // {"Id":1,"Age":22,"First Name":"Dogwei"}
        }
    }

(4): Set the date format

    public class Demo
    {
        public static void Main()
        {
            var jsonFormatter = new JsonFormatter();

            jsonFormatter.SetDateTimeFormat("yyyy-MM-dd HH:mm:ss");

            var json = jsonFormatter.Serialize(DateTime.Now);

            Console.WriteLine(json); // "2019-02-13 11:03:46"
        }
    }

(5): Custom type behavior

    public class Demo
    {
        public string Name { get; set; }

        public int Sex { get; set; }

        public bool IsMan { get => Sex == 1; }

        public unsafe static void Main()
        {
            var jsonFormatter = new JsonFormatter();
            
            jsonFormatter.SetValueInterface<bool>(new MyBooleanInterface());

            var obj = new Demo() { Name = "Dogwei", Sex = 1 };

            var json = jsonFormatter.Serialize(obj);

            Console.WriteLine(json); // {"IsMan":"yes","Name":"Dogwei","Sex":1}
        }
    }

    public class MyBooleanInterface : IValueInterface<bool>
    {
        public bool ReadValue(IValueReader valueReader)
        {
            var value = valueReader.ReadString();

            switch (value)
            {
                case "yes":
                case "true":
                    return true;
                case "no":
                case "false":
                    return false;
                default:
                    return Convert.ToBoolean(value);
            }
        }

        public void WriteValue(IValueWriter valueWriter, bool value)
        {
            valueWriter.WriteString(value ? "yes" : "no");
        }
    }

(6): Set the cache size

    public class Demo
    {
        public static void Main()
        {
            HGlobalCache.MaxSize = 1024 * 500; // 500KB

            var json = JsonFormatter.SerializeObject(new { MaxJsonLength = 256000 });
        }
    }

(7): Serializing oversized files

    public class Demo
    {
        public static void Main()
        {
            var bigObject = new BigObject();

            using (FileStream fileStream = new FileStream("/BigObject.json", FileMode.Create, FileAccess.ReadWrite))
            {
                using (StreamWriter streamWriter = new StreamWriter(fileStream))
                {
                    JsonFormatter.SerializeObject(bigObject, streamWriter);
                }
            }
        }
    }

(8): Use XObjectRW<T> for small applications

    public class Demo
    {
        public static void Main()
        {
           // Default (FastObjectInterface) : The initialization overhead is large, the memory is large, and the performance is excellent.
             // XObjectInterface : The initialization overhead is small, the memory usage is small, and the performance is not bad.

            ValueInterface.DefaultObjectInterfaceType = typeof(XObjectInterface<>);

            var json = JsonFormatter.SerializeObject(new { Id = 1, Name = "Dogwei" });

            Console.WriteLine(json); // {"Id":1,"Name":"Dogwei"}
        }
    }