0

//This is what I have implemented. This works fine. But the problem, when I again submit the data, the old data remove. Only the last inserted data shown in file. I want all the data in Json file when we save.

If anyone has idea, please help me.

public ActionResult Index(UserData model)
{
      try
      {
            // Pass the "personlist" object for conversion object to JSON string  
            string jsondata = new JavaScriptSerializer().Serialize(model);
            string path = Server.MapPath("~/App_Data/output.json");
            // Write that JSON to txt file,  
            System.IO.File.WriteAllText(path , jsondata);
            TempData["msg"] = "Json file Generated! check this in your App_Data folder";
      }
      catch (Exception e) { }
            
      return RedirectToAction("Index");
  }
6
  • Your code is saving all the data and overwriting the file. Did you want to append data to the file perhaps? You can use FIle.AppendAllText but that will produce an invalid JSON file - JSON can't have multiple root elements. Commented Aug 27, 2020 at 10:21
  • Are you trying to store a separate JSON payload per line perhaps? You'd have to serialize the data without newlines first. I'm not sure the obsolete JavaScriptSerializer can do that. Everyone, including Microsoft, is using Json.NET instead, with eg JsonConvert.SerializeObject(model, Formatting.None), then use AppendLine to add a new line to the file Commented Aug 27, 2020 at 10:23
  • {"FirstName":"Himanshu ","LastName":"Mishra","OfficeName":"Hashtag Labs","Email":"[email protected]","Phone":"9988775544","RoleId":0,"RoleName":null} This is my Data. I want to save another data keep this also in the file. So, what's the solution? Commented Aug 27, 2020 at 10:24
  • That comment doesn't explain anything. The current code saves all the data in a single file, so the question by itself is unclear. It would make sense if the real problem was how to append records to a file Commented Aug 27, 2020 at 10:25
  • Yeah, give me solution for save multiple records or append records inn json file? Commented Aug 27, 2020 at 10:27

1 Answer 1

2

I don't have your implementation of UserData, so I took a guess at what it might look like based on your comment. You need to read back the contents of the file if it exists before overwriting it. I use Json.NET and have never used this particular serializer that you are using, but I'm assuming it works. You could do something like this:

public class UserData
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string OfficeName { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public int RoleId { get; set; }
    public string RoleName { get; set; }
}

public ActionResult Index(UserData model)
{
    try
    {
        string path = Server.MapPath("~/App_Data/output.json");
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        string jsonData;
        List<UserData> userDataList = new List<UserData>();

        if (System.IO.File.Exists(path))
        {
            // Read from existing file.
            jsonData = System.IO.File.ReadAllText(path);

            // Fill in the list with the existing user data.
            userDataList.AddRange(serializer.Deserialize<List<UserData>>(jsonData));
        }

        // Add the new user data to the end of the list.
        userDataList.Add(model);

        // Generate JSON based on the complete list.
        jsonData = serializer.Serialize(userDataList);

        // Write that JSON to a file.
        System.IO.File.WriteAllText(path, jsonData);
        TempData["msg"] = "Json file Generated! check this in your App_Data folder";
    }
    catch (Exception e)
    {

    }

    return RedirectToAction("Index");
}
Sign up to request clarification or add additional context in comments.

Comments

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.