I want to save data in local json file in this format:
[
{"Name":"sdafdsf","Password":"dsfads","FirstName":"fsdf","LastName":"dsfdafas"},
{"Name":"sddafdsf","Password":"dsfadds","FirstName":"fdsdf","LastName":"dsfdafasdfs"}
]
I am using this in the controller to serialize into json format:
public ActionResult Index(demo obj)
{
String json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
string path = Server.MapPath("~/app/");
//// Write that JSON to txt file,
//var read = System.IO.File.ReadAllText(path + "output.json");
System.IO.File.WriteAllText(path + "output.json", json);
return View();
}
This is my model:
public class demo
{
public string Name { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
But instead of proper JSON format I am getting this in my output.json file:
{"Name":"sdafdsf","Password":"dsfads","FirstName":"fsdf","LastName":"dsfdafas"}{"Name":"adfsdsfsafdsafasdfsdfsadf","Password":"dfsaasdsa","FirstName":"safd","LastName":"dfsafads"}
How can I save data in the proper format?
This is the proper format, if you mean you need it like an array then add the object to an array and after that serialize it:
public ActionResult Index(demo obj)
{
var array = new [] {obj};
String json = Newtonsoft.Json.JsonConvert.SerializeObject(array);
string path = Server.MapPath("~/app/");
//// Write that JSON to txt file,
//var read = System.IO.File.ReadAllText(path + "output.json");
System.IO.File.WriteAllText(path + "output.json", json);
return View();
}
Or:
var list = new List<demo>();
list.Add(obj);
String json = Newtonsoft.Json.JsonConvert.SerializeObject(list);
if you want to keep data always in an array then you always need to:
like this:
public ActionResult Index(demo obj)
{
string path = Server.MapPath("~/app/");
var read = System.IO.File.ReadAllText(path + "output.json");
List<demo> lst = Newtonsoft.Json.JsonConvert.DeserializeObject<List<demo>>(read);
if (lst == null)
{
List<demo> _data = new List<demo>();
_data.Add(obj);
String json = Newtonsoft.Json.JsonConvert.SerializeObject(_data.ToArray());
System.IO.File.WriteAllText(path + "output.json", json);
}
else
{
lst.Add(obj);
String json = Newtonsoft.Json.JsonConvert.SerializeObject(lst);
System.IO.File.WriteAllText(path + "output.json", json);
}
return View();
}
Of course you can write cleaner code by separate some pieces.