简体   繁体   English

使用 .NET 将数组序列化为 JSON 对象

[英]Serialize an array into JSON objects using .NET

The serialization of the array returns the following JSON:数组的序列化返回如下 JSON:

[{"Code":"AAAA","Description":"Description of AAAA"},{"Code":"BBBB","Description":"Description of BBBB"}]

My goal is to return the following JSON:我的目标是返回以下 JSON:

{"AAAA":{"Description":"Description of AAAA"},"BBBB":{"Description":"Description of BBBB"}}

You can achieve something simliar (not exactly the same you are expecting) if instead of serializing an array, build a temporary Dictionary and serialize it.如果不是序列化数组,而是构建一个临时 Dictionary 并对其进行序列化,那么您可以获得类似的东西(与您期望的不完全相同)。

var dict = new Dictionary<String, YourClass>();
foreach (YourClass yourObj in listOfObjs)
{
    dict[yourObj.Code] = yourObj;
}
// then serialize "dict"

You could add a rule to your JSON serializer to make it avoid serializing "code" property in YourClass , and you will end up with a JSON object exactly as you show in your example.您可以在 JSON 序列化程序中添加一条规则,以使其避免序列化YourClass中的“代码”属性,您最终将得到一个 JSON object 与您的示例完全相同

You'll need to either use a class that has the "AAAA" and "BBBB" properties, or you'll need to serialize a dictionary instead.您需要使用具有“AAAA”和“BBBB”属性的 class,或者您需要序列化字典。 As it is, you're serializing an array and getting an array.实际上,您正在序列化一个数组并获取一个数组。

The table on this blog post shows several search starting points.此博客文章中的表格显示了几个搜索起点。

.Net has built-in System.Web.Script.Serialization.JavaScriptSerializer, here, with examples .Net内置了System.Web.Script.Serialization.JavaScriptSerializer, 这里有例子

The.Net one doesn't specially serialize Dictionary the way you want, but some of the others do, I believe.我相信,.Net 不会以您想要的方式专门序列化 Dictionary,但其他一些会这样做。 However, I think there are reasons NOT to want a general serialization routine the way you've requested - though I can't list them certainly.但是,我认为有理由不想要您要求的通用序列化例程 - 尽管我不能肯定地列出它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM