Steve
Steve

Reputation: 959

C#: Json validation from user input

I need to validate a json file from server side, Im using asp.net mvc with c#, so I have this method in my controller

public ActionResult Validate(HttpPostedFileBase jsonFile) 
    {
        bool validJson = false;
        var serializer = new JavaScriptSerializer();

        try 
        {
            var result = serializer.Deserialize<Dictionary<string, object>>(How should I pass the json file here ??);
            validJson = true;
        } 
        catch(Exception ex)
        {
            validJson = false;
        }

    }

This is the best way for validate it ? ... sorry but I don't know how to pass the json string parameter, I have tried with jsonFile.InputStream.ToString(), jsonFile.tostring() ... what it needs ?, json user's route ? ... thanks in advance

Upvotes: 1

Views: 1033

Answers (1)

Dimitar Dimitrov
Dimitar Dimitrov

Reputation: 15158

Well how about something like this:

using (var reader = new StreamReader(jsonFile.InputStream))
{
    string jsonData = reader.ReadToEnd();
    var serializer = new JavaScriptSerializer();

    var result = serializer.Deserialize<Dictionary<string, object>>(jsonData);
    // dragons be here ...
}

Upvotes: 1

Related Questions