C# 将列表序列化为 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9110724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 06:01:01  来源:igfitidea点击:

Serializing a list to JSON

c#asp.netjson

提问by frenchie

I have an object model that looks like this:

我有一个看起来像这样的对象模型:

public MyObjectInJson
{
   public long ObjectID {get;set;}
   public string ObjectInJson {get;set;}
}

The property ObjectInJsonis an already serialized version an object that contains nested lists. For the moment, I'm serializing the list of MyObjectInJsonmanually like this:

该属性ObjectInJson是一个已经序列化的版本,一个包含嵌套列表的对象。目前,我正在MyObjectInJson像这样手动序列化列表:

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();

I wonder if I can replace this sort of dangerous code with JavascriptSerializerand get the same results. How would I do this?

我想知道我是否可以替换这种危险的代码JavascriptSerializer并获得相同的结果。我该怎么做?

Thanks.

谢谢。

采纳答案by Jodrell

If using .Net Core 3.0 or later;

如果使用 .Net Core 3.0 或更高版本;

Default to using the built in System.Text.Jsonparser implementation.

默认使用内置的System.Text.Json解析器实现。

e.g.

例如

using System.Text.Json;

var json = JsonSerializer.Serialize(aList);

alternatively, other, less mainstream options are available like Utf8Jsonparser and Jil: These may offer superior performance, if you really need it but, you will need to install their respective packages.

或者,还有其他不太主流的选项,如Utf8Json解析器和Jil:这些可能提供卓越的性能,如果您确实需要它,但是,您需要安装它们各自的软件包。

If stuck using .Net Core 2.2 or earlier;

如果使用 .Net Core 2.2 或更早版本卡住;

Default to using Newtonsoft JSON.Net as your first choice JSON Parser.

默认使用 Newtonsoft JSON.Net 作为您的首选 JSON 解析器。

e.g.

例如

using Newtonsoft.Json;

var json = JsonConvert.SerializeObject(aList);

you may need to install the package first.

您可能需要先安装该软件包。

PM> Install-Package Newtonsoft.Json

For more details see and upvote the answer that is the source of this information.

有关更多详细信息,请参阅并支持作为此信息来源的答案

For reference only, this was the original answer, many years ago;

仅供参考,这是多年前的原始答案;

// you need to reference System.Web.Extensions

using System.Web.Script.Serialization;

var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(aList);

回答by Joulukuusi

There are two common ways of doing that with built-in JSON serializers:

使用内置的 JSON 序列化程序有两种常见的方法:

  1. JavaScriptSerializer

    var serializer = new JavaScriptSerializer();
    return serializer.Serialize(TheList);
    
  2. DataContractJsonSerializer

    var serializer = new DataContractJsonSerializer(TheList.GetType());
    using (var stream = new MemoryStream())
    {
        serializer.WriteObject(stream, TheList);
        using (var sr = new StreamReader(stream))
        {
            return sr.ReadToEnd();
        }
    }
    

    Note, that this option requires definition of a data contract for your class:

    [DataContract]
    public class MyObjectInJson
    {
       [DataMember]
       public long ObjectID {get;set;}
       [DataMember]
       public string ObjectInJson {get;set;}
    }
    
  1. JavaScriptSerializer

    var serializer = new JavaScriptSerializer();
    return serializer.Serialize(TheList);
    
  2. DataContractJsonSerializer

    var serializer = new DataContractJsonSerializer(TheList.GetType());
    using (var stream = new MemoryStream())
    {
        serializer.WriteObject(stream, TheList);
        using (var sr = new StreamReader(stream))
        {
            return sr.ReadToEnd();
        }
    }
    

    请注意,此选项需要为您的类定义数据协定:

    [DataContract]
    public class MyObjectInJson
    {
       [DataMember]
       public long ObjectID {get;set;}
       [DataMember]
       public string ObjectInJson {get;set;}
    }
    

回答by Panagiotis Kanavos

.NET already supports basic Json serialization through the System.Runtime.Serialization.Json namespaceand the DataContractJsonSerializerclass since version 3.5. As the name implies, DataContractJsonSerializer takes into account any data annotations you add to your objects to create the final Json output.

从 3.5 版开始,.NET 已经通过System.Runtime.Serialization.Json 命名空间DataContractJsonSerializer类支持基本的 Json 序列化。顾名思义,DataContractJsonSerializer 会考虑您添加到对象中的任何数据注释,以创建最终的 Json 输出。

That can be handy if you already have annotated data classes that you want to serialize Json to a stream, as described in How To: Serialize and Deserialize JSON Data. There are limitations but it's good enough and fast enough if you have basic needs and don't want to add Yet Another Library to your project.

如果您已经有要将 Json 序列化为流的带注释的数据类,这会很方便,如如何:序列化和反序列化 JSON 数据中所述。有一些限制,但如果您有基本需求并且不想将 Yet Another Library 添加到您的项目中,它已经足够好且足够快。

The following code serializea a list to the console output stream. As you see it is a bitmore verbose than Json.NET and not type-safe (ie no generics)

以下代码将一个列表序列化到控制台输出流。正如你看到它是一个有点更详细的比Json.NET,而不是类型安全的(即没有仿制药)

        var list = new List<string> {"a", "b", "c", "d"};

        using(var output = Console.OpenStandardOutput())                
        {                
            var writer = new DataContractJsonSerializer(typeof (List<string>));
            writer.WriteObject(output,list);
        }

On the other hand, Json.NETprovides much better control over how you generate Json. This will come in VERY handy when you have to map javascript-friendly names names to .NET classes, format dates to json etc.

另一方面,Json.NET对生成 Json 的方式提供了更好的控制。当您必须将 javascript 友好名称映射到 .NET 类,将日期格式设置为 json 等时,这将非常方便。

Another option is ServiceStack.Text, part of the ServicStack... stack, which provides a set of very fast serializers for Json, JSV and CSV.

另一个选项是 ServiceStack.Text,它是ServicStack... 堆栈的一部分,它为 Json、JSV 和 CSV 提供了一组非常快速的序列化程序。

回答by Brent Barbata

You can also use Json.NET. Just download it at http://james.newtonking.com/pages/json-net.aspx, extract the compressed file and add it as a reference.

您也可以使用 Json.NET。只需在http://james.newtonking.com/pages/json-net.aspx下载它,提取压缩文件并将其添加为参考。

Then just serialize the list (or whatever object you want) with the following:

然后只需使用以下内容序列化列表(或您想要的任何对象):

using Newtonsoft.Json;

string json = JsonConvert.SerializeObject(listTop10);

Update: you can also add it to your project via the NuGet Package Manager (Tools --> NuGet Package Manager --> Package Manager Console):

更新:您还可以通过 NuGet 包管理器(工具 --> NuGet 包管理器 --> 包管理器控制台)将其添加到您的项目中:

PM> Install-Package Newtonsoft.Json

Documentation: Serializing Collections

文档:序列化集合

回答by samsanthosh2008

public static string JSONSerialize<T>(T obj)
        {
            string retVal = String.Empty;
            using (MemoryStream ms = new MemoryStream())
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                serializer.WriteObject(ms, obj);
                var byteArray = ms.ToArray();
                retVal = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
            }
            return retVal;
        }

回答by Joseph Ptheitroadier

building on an answer from another posting.. I've come up with a more generic way to build out a list, utilizing dynamic retrieval with Json.NET version 12.x

建立在另一个帖子的答案上..我想出了一种更通用的方法来构建列表,利用 Json.NET 12.x 版的动态检索

using Newtonsoft.Json;

static class JsonObj
{
    /// <summary>
    /// Deserializes a json file into an object list
    /// Author: Joseph Ptheitroadier 2/26/2019
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="fileName"></param>
    /// <returns></returns>
    public static List<T> DeSerializeObject<T>(string fileName)
    {
        List<T> objectOut = new List<T>();

        if (string.IsNullOrEmpty(fileName)) { return objectOut; }

        try
        {
            // reading in full file as text
            string ss = File.ReadAllText(fileName);

            // went with <dynamic> over <T> or <List<T>> to avoid error..
            //  unexpected character at line 1 column 2
            var output = JsonConvert.DeserializeObject<dynamic>(ss);

            foreach (var Record in output)
            {
                foreach (T data in Record)
                {
                    objectOut.Add(data);
                }
            }
        }
        catch (Exception ex)
        {
            //Log exception here
            Console.Write(ex.Message);
        }

        return objectOut;
    }
}

call to process

调用处理

{
        string fname = "../../Names.json"; // <- your json file path

        // for alternate types replace string with custom class below
        List<string> jsonFile = JsonObj.DeSerializeObject<string>(fname);
}

or this call to process

或者这个调用处理

{
        string fname = "../../Names.json"; // <- your json file path

        // for alternate types replace string with custom class below
        List<string> jsonFile = new List<string>();
        jsonFile.AddRange(JsonObj.DeSerializeObject<string>(fname));
}