如何将c#匿名类型序列化为JSON字符串?

时间:2022-12-30 07:21:22

I'm attempting to use the following code to serialize an anonymous type to JSON:

我正在尝试使用以下代码将匿名类型序列化为JSON:

var serializer = new DataContractJsonSerializer(thing.GetType());
var ms = new MemoryStream();
serializer.WriteObject(ms, thing);
var json = Encoding.Default.GetString(ms.ToArray()); 

However, I get the following exception when this is executed:

但是,执行时我有以下例外:

Type '<>f__AnonymousType1`3[System.Int32,System.Int32,System.Object[]]' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. See the Microsoft .NET Framework documentation for other supported types.

类型的< > f__AnonymousType1 3[System.Int32、System.Int32、系统。对象[]]“不能被序列化。考虑使用DataContractAttribute属性对其进行标记,并标记您希望使用DataMemberAttribute属性序列化的所有成员。参见Microsoft . net框架文档了解其他支持类型。

I can't apply attributes to an anonymous type (as far as I know). Is there another way to do this serialization or am I missing something?

我不能对匿名类型应用属性(据我所知)。还有其他方法可以进行序列化吗?还是我漏掉了什么?

7 个解决方案

#1


150  

Try the JavaScriptSerializer instead of the DataContractJsonSerializer

尝试使用JavaScriptSerializer而不是DataContractJsonSerializer

JavaScriptSerializer serializer = new JavaScriptSerializer();
var output = serializer.Serialize(your_anon_object);

#2


59  

As others have mentioned, Newtonsoft JSON.NET is a good option. Here is a specific example for simple JSON serialization:

正如其他人提到的,Newtonsoft JSON。NET是一个不错的选择。这里有一个简单的JSON序列化的具体示例:

return JsonConvert.SerializeObject(
    new
    {
       DataElement1,
       SomethingElse
    });

I have found it to be a very flexible, versatile library.

我发现它是一个灵活多变的图书馆。

#3


12  

You can try my ServiceStack JsonSerializer it's the fastest .NET JSON serializer at the moment. It supports serializing DataContract's, Any POCO Type, Interfaces, Late-bound objects including anonymous types, etc.

你可以试试我的ServiceStack JsonSerializer它是目前最快的。net JSON序列化器。它支持序列化DataContract,任何POCO类型,接口,后期绑定对象,包括匿名类型等。

Basic Example

基本的例子

var customer = new Customer { Name="Joe Bloggs", Age=31 };
var json = customer.ToJson();
var fromJson = json.FromJson<Customer>(); 

Note: Only use Microsofts JavaScriptSerializer if performance is not important to you as I've had to leave it out of my benchmarks since its up to 40x-100x slower than the other JSON serializers.

注意:如果性能对您不重要的话,请只使用Microsofts JavaScriptSerializer,因为我不得不把它排除在我的基准测试之外,因为它比其他JSON序列化器慢了40x-100x。

#4


10  

I would argue that you shouldn't be serializing an anonymous type. I know the temptation here; you want to quickly generate some throw-away types that are just going to be used in a loosely type environment aka Javascript in the browser. Still, I would create an actual type and decorate it as Serializable. Then you can strongly type your web methods. While this doesn't matter one iota for Javascript, it does add some self-documentation to the method. Any reasonably experienced programmer will be able to look at the function signature and say, "Oh, this is type Foo! I know how that should look in JSON."

我认为您不应该序列化匿名类型。我知道这里的诱惑;您希望快速生成一些一次性类型,这些类型将在松散类型的环境(即浏览器中的Javascript)中使用。尽管如此,我还是要创建一个实际的类型并将其修饰为Serializable。然后您可以强类型您的web方法。虽然这对Javascript来说一点iota都不重要,但它确实向方法添加了一些自文档。任何有经验的程序员都可以查看函数签名并说,“噢,这是Foo类型!”我知道JSON的样子"

Having said that, you might try JSON.Net to do the serialization. I have no idea if it will work

说到这里,您可以尝试JSON。Net进行序列化。我不知道它会不会有用

#5


7  

The fastest way I found was this:

我找到的最快的方法是:

var obj = new {Id = thing.Id, Name = thing.Name, Age = 30};
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(obj);

Namespace: System.Web.Script.Serialization.JavaScriptSerializer

名称空间:System.Web.Script.Serialization.JavaScriptSerializer

#6


1  

Assuming you are using this for a web service, you can just apply the following attribute to the class:

假设您正在对web服务使用此属性,那么您只需将以下属性应用到该类:

[System.Web.Script.Services.ScriptService]

Then the following attribute to each method that should return Json:

然后,每个方法的以下属性应该返回Json:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

And set the return type for the methods to be "object"

并将方法的返回类型设置为“object”

#7


-1  

public static class JsonSerializer
{
    public static string Serialize<T>(this T data)
    {
        try
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            var stream = new MemoryStream();
            serializer.WriteObject(stream, data);
            string jsonData = Encoding.UTF8.GetString(stream.ToArray(), 0, (int)stream.Length);
            stream.Close();
            return jsonData;
        }
        catch
        {
            return "";
        }
    }
    public static T Deserialize<T>(this string jsonData)
    {
        try
        {
            DataContractJsonSerializer slzr = new DataContractJsonSerializer(typeof(T));
            var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonData));
            T data = (T)slzr.ReadObject(stream);
            stream.Close();
            return data;
        }
        catch
        {
            return default(T);
        }
    }
}

#1


150  

Try the JavaScriptSerializer instead of the DataContractJsonSerializer

尝试使用JavaScriptSerializer而不是DataContractJsonSerializer

JavaScriptSerializer serializer = new JavaScriptSerializer();
var output = serializer.Serialize(your_anon_object);

#2


59  

As others have mentioned, Newtonsoft JSON.NET is a good option. Here is a specific example for simple JSON serialization:

正如其他人提到的,Newtonsoft JSON。NET是一个不错的选择。这里有一个简单的JSON序列化的具体示例:

return JsonConvert.SerializeObject(
    new
    {
       DataElement1,
       SomethingElse
    });

I have found it to be a very flexible, versatile library.

我发现它是一个灵活多变的图书馆。

#3


12  

You can try my ServiceStack JsonSerializer it's the fastest .NET JSON serializer at the moment. It supports serializing DataContract's, Any POCO Type, Interfaces, Late-bound objects including anonymous types, etc.

你可以试试我的ServiceStack JsonSerializer它是目前最快的。net JSON序列化器。它支持序列化DataContract,任何POCO类型,接口,后期绑定对象,包括匿名类型等。

Basic Example

基本的例子

var customer = new Customer { Name="Joe Bloggs", Age=31 };
var json = customer.ToJson();
var fromJson = json.FromJson<Customer>(); 

Note: Only use Microsofts JavaScriptSerializer if performance is not important to you as I've had to leave it out of my benchmarks since its up to 40x-100x slower than the other JSON serializers.

注意:如果性能对您不重要的话,请只使用Microsofts JavaScriptSerializer,因为我不得不把它排除在我的基准测试之外,因为它比其他JSON序列化器慢了40x-100x。

#4


10  

I would argue that you shouldn't be serializing an anonymous type. I know the temptation here; you want to quickly generate some throw-away types that are just going to be used in a loosely type environment aka Javascript in the browser. Still, I would create an actual type and decorate it as Serializable. Then you can strongly type your web methods. While this doesn't matter one iota for Javascript, it does add some self-documentation to the method. Any reasonably experienced programmer will be able to look at the function signature and say, "Oh, this is type Foo! I know how that should look in JSON."

我认为您不应该序列化匿名类型。我知道这里的诱惑;您希望快速生成一些一次性类型,这些类型将在松散类型的环境(即浏览器中的Javascript)中使用。尽管如此,我还是要创建一个实际的类型并将其修饰为Serializable。然后您可以强类型您的web方法。虽然这对Javascript来说一点iota都不重要,但它确实向方法添加了一些自文档。任何有经验的程序员都可以查看函数签名并说,“噢,这是Foo类型!”我知道JSON的样子"

Having said that, you might try JSON.Net to do the serialization. I have no idea if it will work

说到这里,您可以尝试JSON。Net进行序列化。我不知道它会不会有用

#5


7  

The fastest way I found was this:

我找到的最快的方法是:

var obj = new {Id = thing.Id, Name = thing.Name, Age = 30};
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(obj);

Namespace: System.Web.Script.Serialization.JavaScriptSerializer

名称空间:System.Web.Script.Serialization.JavaScriptSerializer

#6


1  

Assuming you are using this for a web service, you can just apply the following attribute to the class:

假设您正在对web服务使用此属性,那么您只需将以下属性应用到该类:

[System.Web.Script.Services.ScriptService]

Then the following attribute to each method that should return Json:

然后,每个方法的以下属性应该返回Json:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

And set the return type for the methods to be "object"

并将方法的返回类型设置为“object”

#7


-1  

public static class JsonSerializer
{
    public static string Serialize<T>(this T data)
    {
        try
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            var stream = new MemoryStream();
            serializer.WriteObject(stream, data);
            string jsonData = Encoding.UTF8.GetString(stream.ToArray(), 0, (int)stream.Length);
            stream.Close();
            return jsonData;
        }
        catch
        {
            return "";
        }
    }
    public static T Deserialize<T>(this string jsonData)
    {
        try
        {
            DataContractJsonSerializer slzr = new DataContractJsonSerializer(typeof(T));
            var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonData));
            T data = (T)slzr.ReadObject(stream);
            stream.Close();
            return data;
        }
        catch
        {
            return default(T);
        }
    }
}