保存数据以JSON格式使用C#

我想在本地JSON文件数据保存格式为:保存数据以JSON格式使用C#

[ 

{"Name":"sdafdsf","Password":"dsfads","FirstName":"fsdf","LastName":"dsfdafas"},

{"Name":"sddafdsf","Password":"dsfadds","FirstName":"fdsdf","LastName":"dsfdafasdfs"}

]

我用这在控制器序列化为JSON格式:

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();

}

这是我的模型:

public class demo 

{

public string Name { get; set; }

public string Password { get; set; }

public string FirstName { get; set; }

public string LastName { get; set; }

}

但不是正确的JSON格式我得到这在我的output.json文件中:

{"Name":"sdafdsf","Password":"dsfads","FirstName":"fsdf","LastName":"dsfdafas"}{"Name":"adfsdsfsafdsafasdfsdfsadf","Password":"dfsaasdsa","FirstName":"safd","LastName":"dfsafads"} 

我如何保存数据格式正确?

回答:

这是正确的格式,如果你的意思是你需要它像一个数组,然后将对象添加到一个数组,之后对其进行序列化:

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();

}

或者:

var list = new List<demo>(); 

list.Add(obj);

String json = Newtonsoft.Json.JsonConvert.SerializeObject(list);

,如果你要在数组始终保持数据,那么你总是需要:从JSON文件

  1. 读取数据。
  2. 作为`List'列表脱盐。
  3. 将新项目添加到此列表中。
  4. 再次序列化它并将其保存在该文件中,用新文件替换所有旧文本。

这样的:

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();

}

当然你也可以通过写一些独立片更干净的代码。

回答:

先创建一个对象列表,然后尝试序列化列表。我相信你会得到所需的输出。看起来像您使用AppendAllText方法通过序列化单个对象。

以上是 保存数据以JSON格式使用C# 的全部内容, 来源链接: utcz.com/qa/264828.html

回到顶部