0

I have a Json file as shown below. I want to convert only the option node in the JSON file into a C# ListItemCollection object

ASP.net File:

   var path = Server.MapPath(@"~/json.json");
    using (StreamReader r = new StreamReader(path,false))
    {                      
        string json = r.ReadToEnd();
        dynamic arr = JsonConvert.DeserializeObject(json);
        ListItemCollection licRB = new ListItemCollection();  
        licRB = arr.AnswerRadioButton.option;<<-- run time error is produced here 
    }

JSON File:

{   "FormTitle": "This is Form Title from JSON",
  "TitleQuestion1": "This is the Title of Question 1",
  "TextQuestion1": "1- This is the text of Quextion Number 1",
  "AnswerRadioButton": {
"visible": "true",
"title": "Radio Button Title",
"FieldsetRBStyle": { "border": "1px" },
"option" : [
  {
    "text": "text1",
    "value": "v1",
    "checked": "false"
  },
  {
    "text": "text2",
    "value": "v2",
    "checked": "true"
  },
  {
    "text": "text3",
    "value": "v3",
    "checked": "false"
  },
  {
    "text": "text4",
    "value": "v4",
    "checked": "true"
  }
]  }}
Shomaail
  • 493
  • 9
  • 30
  • Have you tried `Convert.ChangeTo(arr.AnswerRadioButton.option, TypeOf(ListViewCollection))`? You might need to do it on a per-item basis if that fails. Basically, you cannot cast dynamic types unless they fit certain condition, but you can convert them. – JasonX Nov 29 '16 at 08:16

1 Answers1

1

Assuming that you have the required classes (e.g. using this tool) you can access the options like this:

var test = JsonConvert.DeserializeObject<RootObject>(json);
var options = test.AnswerRadioButton.option;
Mahdi
  • 3,199
  • 2
  • 25
  • 35
  • is there a way to generate class from JSON file on run time instead of using this tool – Shomaail Nov 29 '16 at 08:44
  • -- Yes I found http://stackoverflow.com/questions/21611674/how-to-auto-generate-a-c-sharp-class-file-from-a-json-object-string – Shomaail Nov 29 '16 at 08:51