JSON conversions

Asked

Viewed 154 times

2

I’m a beginner in C# and ASP.NET, and I’m having doubts about JSON and dictionaries

I have a serialized Dictionary that was stored in the database with:

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

After serialized this Dictionary it is stored in the database, because this information I will use later in a view (Popup in Asp.net).

My difficulty is in deserializar these values that are in the database to put them back in a Dictionary. I tried:

Code you used to recoil the information in the database:

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

The only way to collect the information in code Behind was:

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

However, I cannot use it with iterations and it is not even a Dictionary. With Dictionary I used the following code snippet:

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

I mean, when I need .Add to chave and the valor in my Dictionary not only do I have a large string which is the value I get in Literal:

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

How can I make this conversion the right way? Thank you.

1 answer

0

Solved:

I used the Json.NET framework applied by Nugget in Visual Studio 2015 and imported it into the project:

using Newtonsoft.Json;

I got the values from . aspx:

string serializada = @"" + ((Literal)e.Item.FindControl("lblFiltros")).Text

And to deserialize I used the following command:

Dictionary<string, string> valores = JsonConvert.DeserializeObject<Dictionary<string, string>>(serializada);

Obs.: the method JsonConvert belongs to the imported package.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.