简体   繁体   English

在字典C#中转换JSON

[英]Converting JSON in Dictionary C#

I'm beginner to C # and ASP.NET , however I have some doubts. 我是C#和ASP.NET的初学者,但是我有一些疑问。

It has a serialized dictionary que was stored in the database with : 它具有一个序列化的字典que,它与一起存储在数据库中:

    var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(filters.ToDictionary(item => item.Key.ToString(), item => item.Value.ToString()));

After serialized this dictionary it is stored in the database , because I'll use information in a view (PopUp in asp.net). 将此字典序列化后,它会存储在数据库中,因为我将在视图(asp.net中的PopUp)中使用信息。

My difficulty is deserialize these values ​​that are in the database to put them back in a dictionary. 我的困难是反序列化数据库中的这些值以将它们放回字典中。 I tried: 我试过了:

Code used to get the information in the database : 用于获取数据库中信息的代码:

<asp:Literal ID="lblFilter" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "FilterJson")%> ' />

The only way I get to collect the information in the code behind was: 我收集背后代码中信息的唯一方法是:

object filter = new System.Web.Script.Serialization.JavaScriptSerializer().DeserializeObject(((Literal)e.Item.FindControl("lblFilter")).Text);

However , I can't use it with iterations and not even a Dictionary. 但是,我不能将其与迭代一起使用,甚至不能与Dictionary一起使用。 With Dictionary used the following code: 与Dictionary一起使用以下代码:

System.Collections.Generic.Dictionary<string, string> filters = new System.Collections.Generic.Dictionary<string, string>();

That is when I need .Add a key and value in my dictionary not only chain I have a great What is the value que get no Literal : 那是当我需要.Add一个keyvalue在我的字典里,不仅连锁我有一个伟大的什么是价值阙拿不出Literal

((Literal)e.Item.FindControl("lblFilter")).Text

How can I make to converting correctly ? 如何正确转换? Thank you. 谢谢。

To deserialize a JSON-string you can easily use the following code: 要反序列化JSON字符串,您可以轻松使用以下代码:

Dictionary<object, object> filters = new JavaScriptSerializer().Deserialize<Dictionary<object, object>>(yourJSONString);

You have to use object instead of string , because if you have a list in your JSON-string you will get an error. 您必须使用object而不是string ,因为如果您的JSON字符串中有一个列表,则会出现错误。

Solved: 解决了:

I used the framework Json.NET regardless package in project. 无论项目中的软件包如何,我都使用框架Json.NET。

using Newtonsoft.Json;

Getting .aspx values: 获取.aspx值:

string serialize = @"" + ((Literal)e.Item.FindControl("lblFilter")).Text

To deserialize I used code bellow: 为了反序列化,我使用下面的代码:

Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(serialize);

Obs.: the JsonConvert method belongs to the import package. JsonConvertJsonConvert方法属于导入包。

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

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