0

I have a json string as following

string json = "{\"Method\":\"LOGIN\",\"Skill\":{\"1\":\"SKILL-1\",\"2\":\"SKILL-2\"}}";

I am using JavaScriptSerializer to parse json

System.Web.Script.Serialization.JavaScriptSerializer oSerializer = 
                               new System.Web.Script.Serialization.JavaScriptSerializer();
var dict = oSerializer.Deserialize<Dictionary<string,object>>(json);

I am getting Method = LOGIN using following line

MessageBox.Show("Method = "+dict["Method"].ToString());

But how to get Skill in a loop. like

Skill

1 = SKILL-1
2 = SKILL-2
MD SHAHIDUL ISLAM
  • 14,325
  • 6
  • 82
  • 89
  • Consider deserializing the JSON to a custom type containing the `Method` as a string, and the `Skill` as a `Dictionary`. Then iterate the dictionary. – aevitas Feb 17 '15 at 12:44
  • possible duplicate of [How to parse json in C#?](http://stackoverflow.com/questions/6620165/how-to-parse-json-in-c) – Ajay Feb 17 '15 at 12:49

3 Answers3

1

You should declare your own class:

public class YourClassName
{
    public string Method { get; set; }
    public Dictionary<int, string> Skill { get; set; }
}

and deserialize the Json string like this:

var obj = oSerializer.Deserialize<YourClassName>(json);
SmartDev
  • 2,802
  • 1
  • 17
  • 22
1

The value mapping to your Skill key is actually another Dictionary<string, object>. You can iterate it by casting the object:

string json = "{\"Method\":\"LOGIN\",\"Skill\":{\"1\":\"SKILL-1\",\"2\":\"SKILL-2\"}}";

var oSerializer = new JavaScriptSerializer();
var dict = oSerializer.Deserialize<Dictionary<string,object>>(json);

var innerDict = dict["Skill"] as Dictionary<string, object>;

if (innerDict != null)
{
   foreach (var kvp in innerDict)
   {
       Console.WriteLine ("{0} = {1}", kvp.Key, kvp.Value);
   }
}

Or, the alternative would be to map your object into a proper class and deserialize to it instead of a generic Dictionary<string, object>.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
1

Suppose you have following class

public class Data
{
     public string Method { get; set; }
     public Skills Skill { get; set; }
     // If you don't want to use Skills class then you can use this
     //public Dictionary<int, string> Skills { get; set; }
}
public class Skills
{
     public int Id { get; set; }
     public string Skill { get; set; }
}

So you can Deserialize json into Data Object like this

Data deserializedData = JsonConvert.DeserializeObject<Data>(json);
Ajay
  • 6,418
  • 18
  • 79
  • 130