将列表序列化为 JSON [英] Serializing a list to JSON
问题描述
我有一个看起来像这样的对象模型:
I have an object model that looks like this:
public MyObjectInJson
{
public long ObjectID {get;set;}
public string ObjectInJson {get;set;}
}
属性 ObjectInJson
是一个已经序列化的版本,一个包含嵌套列表的对象.目前,我正在像这样手动序列化 MyObjectInJson
的列表:
The property ObjectInJson
is an already serialized version an object that contains nested lists. For the moment, I'm serializing the list of MyObjectInJson
manually like this:
StringBuilder TheListBuilder = new StringBuilder();
TheListBuilder.Append("[");
int TheCounter = 0;
foreach (MyObjectInJson TheObject in TheList)
{
TheCounter++;
TheListBuilder.Append(TheObject.ObjectInJson);
if (TheCounter != TheList.Count())
{
TheListBuilder.Append(",");
}
}
TheListBuilder.Append("]");
return TheListBuilder.ToString();
我想知道我是否可以用 JavascriptSerializer
替换这种危险的代码并获得相同的结果.我该怎么做?
I wonder if I can replace this sort of dangerous code with JavascriptSerializer
and get the same results.
How would I do this?
推荐答案
如果使用 .Net Core 3.0 或更高版本;
默认使用内置的 System.Text.Json
解析器实现.
例如
using System.Text.Json;
var json = JsonSerializer.Serialize(aList);
或者,也可以使用其他不太主流的选项,例如 Utf8Json 解析器和 Jil:这些可能提供 卓越的性能,如果你真的需要它但是,你需要安装它们各自的包.
alternatively, other, less mainstream options are available like Utf8Json parser and Jil: These may offer superior performance, if you really need it but, you will need to install their respective packages.
默认使用 Newtonsoft JSON.Net 作为您的首选 JSON 解析器.
Default to using Newtonsoft JSON.Net as your first choice JSON Parser.
例如
using Newtonsoft.Json;
var json = JsonConvert.SerializeObject(aList);
您可能需要先安装软件包.
you may need to install the package first.
PM> Install-Package Newtonsoft.Json
有关更多详细信息查看并投票支持作为此信息来源的答案.
// you need to reference System.Web.Extensions
using System.Web.Script.Serialization;
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(aList);
这篇关于将列表序列化为 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!