I have following JSON saved in menu.json file:
{
"menu": {
"menuitems": [
{
"label": "Account",
"listview": "Account List"
},
{
"label": "Documents",
"listview": "Document List"
}
]
}
}
I have written this data to the file manually.I retrieve this data using following function:
public ActionResult GetFromFile(string path)// path points to the menu.json file
{
StreamReader sr = new StreamReader(path);
string filedata = sr.ReadToEnd();
Menu menu = JsonSerializer.DeserializeToString<Menu>(filedata);
return Json(menu, JsonRequestBehavior.Allowget);
}
When I get the response as menu , I am not able to get it separated in the class fields. moreover, I have a single class and so how do I store my json file data to this class?? Will there be any modifications in the class structure? My Menu Class is as follows:
public class Menu
{
public string Label {get;set;}
public string Listview {get;set;}
}
The serialization has an extra, unnamed container above menu. Your class structure needs to look like:
public class container
{
public menu menu { get; set; }
}
public class menu
{
public menuitem[] menuitems { get; set; }
}
public class menuitem
{
public string Label { get; set; }
public string Listview { get; set; }
}
And to deserialize, you can use:
JavaScriptSerializer js = new JavaScriptSerializer();
StreamReader sr = new StreamReader("menu.json");
string filedata = sr.ReadToEnd();
var menus = js.Deserialize<container>(filedata);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With