0

I am trying to send a key-pair based array object using ajax, here array is created dynamically

["{\"key\":\"#c1\",\"value\":\"g1\"}","{\"key\":\"#c1\",\"value\":\"g2\"}",   "{\"key\":\"#c2\",\"value\":\"g3\"}", "{\"key\":\"#c4\",\"value\":\"g4\"}"]

Above is json formatted data which i am sending to a method and able to receive it. At c# end Dictionary<string, string> Columns is used. problem here is that the key values are just number and values contain each element of above mentioned json data as shown below,

 foreach(var eachVals in  columns)
 {
     string k = eachVals.Key;
     string col = eachVals.Value;

 }

when iterating the dictionary eachVals.key is array index (0,1,...) and eachVals.Value contains {"key":"#c1","value":"g1"} So what i want is separate keys i.e "#c1","#c1","#c2"... and values i.e "g1","g2"...

2 Answers 2

1

You would need to deserialize the values from col. Using Newtonsoft.Json, would look something like this:

Dictionary<string, string> columns = new Dictionary<string, string>
        {
            { @"0", @"{""key"": ""#c1"", ""value"":""g1"" }" },
            { @"1", @"{""key"": ""#c2"", ""value"":""g2"" }" }
        };

        var result = columns.ToDictionary(
                                column => JsonConvert.DeserializeObject<MyObj>(column.Value).key, 
                                column => JsonConvert.DeserializeObject<MyObj>(column.Value).value);

Where MyObj is:

internal class MyObj
{
    public string key { get; set; }
    public string value { get; set; }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I think you can do or get the idea from this:

foreach(var eachVals in columns)
 {
     var e = eachVals.Value.Split(',');
     e = e[0].Split(':');
     string k = e[0];
     string v = e[1];
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.