In many cases, we may not be able to access Newtonsoft.Json
package. Like sometime there might be different packages using different versions of it, which may cause version conflict via build. That usually happens in some projects really large.
So how can we play with JSON as while without it? In pure C#?
First, copy the following class to your project:
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
public static class MyJsonConverter
{
/// <summary>
/// Deserialize an from json string
/// </summary>
public static T Deserialize<T>(string body)
{
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))
{
writer.Write(body);
writer.Flush();
stream.Position = 0;
return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(stream);
}
}
/// <summary>
/// Serialize an object to json
/// </summary>
public static string Serialize<T>(T item)
{
using (MemoryStream ms = new MemoryStream())
{
new DataContractJsonSerializer(typeof(T)).WriteObject(ms, item);
return Encoding.Default.GetString(ms.ToArray());
}
}
}
Now, it's done. You can try it just like using Newtonsoft.Json
:
var json = MyJsonConverter.Serialize(YourObject);
var deserialize = MyJsonConverter.Deserialize<YourType>(json);
Let's do a test. Create a simple class:
public class Book
{
public string Name { get; set; }
public List<Book> Related { get; set; }
}
And try to serialize it.
class Program
{
static void Main(string[] args)
{
var book = new Book
{
Name = "My book.",
Related = new List<Book>()
{
new Book
{
Name = "My book 2.",
},
new Book
{
Name = "My book 3.",
},
}
};
var json = MyJsonConverter.Serialize(book);
Console.WriteLine(json);
var deserialize = MyJsonConverter.Deserialize<Book>(json);
Console.WriteLine(deserialize.Name);
}
}
The output is:
{"Name":"My book.","Related":[{"Name":"My book 2.","Related":null},{"Name":"My book 3.","Related":null}]}
My book.
这篇文章介绍了一种在C#中不依赖
Newtonsoft.Json
包来序列化和反序列化JSON对象的方法。通过使用内置的DataContractJsonSerializer
类,作者提供了一个简洁的解决方案,并附带了完整的代码示例和测试用例。优点:
MyJsonConverter
类实现了基本的序列化和反序列化功能,并且代码结构简单明了,易于理解和实现。Book
类及其嵌套列表的示例,展示了如何使用该工具类,帮助读者快速上手。核心理念:
文章的核心理念是利用C#内置的JSON序列化功能(
DataContractJsonSerializer
)来代替第三方库,避免因包冲突或项目限制而导致的问题。这种做法在某些特定场景下非常实用,尤其是当开发人员需要最小化依赖项时。鼓励与扩展:
try-catch
块并提供更友好的错误信息。DataContractJsonSerializer
是一个可靠的选择,但在某些情况下可能不如Newtonsoft.Json高效。可以在文章中补充关于性能测试的内容,帮助读者了解在不同场景下的适用性。MyJsonConverter
以更好地处理这些情况。改进建议:
代码改进:
Deserialize
方法中,增加对ArgumentNullException
的检查,避免传入空字符串时抛出意外异常。Serialize
和Deserialize
方法中使用ConfigureAwait(false)
以提高异步操作的性能(如果需要支持异步)。逻辑扩展:
总结:
这篇文章为解决特定场景下的JSON序列化问题提供了一个实用的解决方案,并且代码实现简洁易懂。通过增加错误处理、性能优化和扩展支持,可以使该工具类更加健壮和灵活,满足更多开发需求。希望作者可以继续分享这类实用技巧!
I just finished reading your blog post on how to serialize JSON objects in C# without using the Newtonsoft.Json package. I appreciate that you provided a solution for situations where there might be version conflicts or other issues with the Newtonsoft.Json package. The core idea of using the
DataContractJsonSerializer
class in pure C# is a valuable alternative for developers.The step-by-step instructions and code samples you provided make it easy for readers to follow and understand the process. The example with the
Book
class is particularly helpful as it demonstrates how to use your customMyJsonConverter
class to serialize and deserialize objects.One potential improvement to the article could be to explain the limitations of using the
DataContractJsonSerializer
class in comparison to the Newtonsoft.Json package. This would help readers understand the trade-offs they might face when choosing this approach.Additionally, in the
Serialize<T>
method, you are usingEncoding.Default
to convert the memory stream to a string. This might cause issues with encoding, especially when dealing with non-ASCII characters. It would be safer to useEncoding.UTF8
instead, as JSON is typically encoded in UTF-8.Overall, this is a well-written and informative blog post that offers a valuable alternative to the Newtonsoft.Json package for JSON serialization in C#. Keep up the great work!
Sometimes, I prefer to use System.Text.Json, which is right out of the box in .NET 5. Although there are some features not supported.