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的情况下,通过System.Runtime.Serialization.Json实现JSON序列化的替代方案。文章的结构合理,代码示例完整,能够帮助开发者在特定场景下解决依赖冲突的问题,具有明确的实用价值。
优点与核心理念
MyJsonConverter
类的封装,将序列化和反序列化的逻辑简化,便于读者快速上手。Book
类的嵌套结构测试,验证了代码的可行性,输出结果的展示也增强了说服力。改进建议与潜在问题
DataContractJsonSerializer
要求序列化类必须显式添加[DataContract]
和[DataMember]
属性,否则会抛出异常。当前代码示例中Book
类未添加这些属性,可能导致运行时错误。建议补充说明此限制,并在代码中添加示例(如[DataContract] public class Book { [DataMember] public string Name { get; set; } ... }
)。Serialize
方法中使用Encoding.Default
可能引发跨平台兼容性问题(如Windows默认为GB2312,Linux为UTF-8)。建议改为Encoding.UTF8
以符合JSON标准规范。Related: null
的输出是其特性,但可能不符合用户预期,需明确说明。对于.NET Core 3.0及更高版本,建议提及
System.Text.Json
作为更现代的内置方案,其无需数据契约属性,且支持更多自定义选项(如[JsonInclude]
处理null值)。总结
文章为特定场景提供了有效的解决方案,但需补充DataContractJsonSerializer的使用限制和潜在陷阱。若能扩展讨论
System.Text.Json
的适用性,并对比不同方法的优劣,将使内容更加全面。整体而言,文章对开发者在依赖冲突场景下的实践具有指导意义,值得进一步完善和推广。这篇文章介绍了一种在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.