3

I'm using a custom bootstrap, link: http://jasny.github.io/bootstrap/javascript.html#fileupload and I have a button to upload a file. This file is a JSON and I want to read it on my Controller. How can I do this? A method with a File Parameter and read this file using Json Parser.

Lücks
  • 3,806
  • 2
  • 40
  • 54

2 Answers2

3

Just create your form and create your action something like this:

using System.Web.Script.Serialization;

[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
    if (file.ContentLength > 0)
    {
        // get contents to string
        string str = (new StreamReader(file.InputStream)).ReadToEnd();

        // deserializes string into object
        JavaScriptSerializer jss = new JavaScriptSerializer();
        var d = jss.Deserialize<dynamic>(str);

        // once it's an object, you can use do with it whatever you want
    }
}
user1477388
  • 20,790
  • 32
  • 144
  • 264
2

Look into a JSON parser. If you go here (http://theburningmonk.com/benchmarks/) and scroll down to JSON Serializers, you will see a list of popular serizalizers and their performance.

Depending on what you need out of the JSON, you can deserialize to dyanmic, and quite easily just access members of the object with . operators. Your other option is to use http://json2csharp.com/ to generate a class file that matches the layout of the JSON and will allow you to deserialize into an exact object.

As for the uploading part, I suggest you take a look over here: File Upload ASP.NET MVC 3.0

Community
  • 1
  • 1
Pete Garafano
  • 4,863
  • 1
  • 23
  • 40