1

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

1 Answer 1

1

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 ...
}
Sign up to request clarification or add additional context in comments.

4 Comments

could you explain to me please, why after using command, I try to save my file and It´s empty, after validate json I need to save some records in db and after all, save my file. But It's only working inside using, and I need it after it ... thank you
You need to save the JSON like: jsonFile.SaveAs("c:\\fullfilepath");
Ok that's exactly what I'm doing but I always get and empty file, I'm trying without those lines and It saves good. I need to save it inside using tag ?
Hmmm, not sure, basically it's disposing of the StreamReader, I'm surprised it's affecting the original InputStream. I'll run some tests.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.