[英]Json.NET Not serializing to file
Even using an example from the Documentation , I still can't find a way to successfully serialize to a file. 即使使用Documentation中的示例,我仍然找不到成功序列化到文件的方法。
Code: 码:
Program.cs Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;
using System.Threading;
namespace TestProject
{
class Program
{
static void Main(string[] args)
{
Item i = new Item
{
Username = "user",
Email = "user@user.com",
Password = "password"
};
File.WriteAllText(@"C:\users\user1.json", JsonConvert.SerializeObject(i));
using (StreamWriter file = File.CreateText(@"C:\users\user1.json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, i);
}
}
}
}
Item.cs Item.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestProject
{
public class Item
{
public string Email { get; set; }
public string Password { get; set; }
public string Username { get; set; }
}
}
When I run Program.cs, it shows no errors, but the JSON does not show in the file. 当我运行Program.cs时,它没有显示错误,但是JSON没有显示在文件中。
When I run your code I get a an exception writing to the users folder. 当我运行您的代码时,出现一个异常写入用户文件夹。 Changing to my home folder works fine.
更改到我的主文件夹可以正常工作。 I suspect this is your problem.
我怀疑这是您的问题。
Addtionally, you're writing the file twice. 另外,您要写入两次文件。 The first time is showing an example of using the SerializeObject method to get a string back which is used with WriteAllText.
第一次显示了使用SerializeObject方法获取与WriteAllText一起使用的字符串的示例。 The second block of code is using a StreamWriter.
第二个代码块使用StreamWriter。 For your purposes, both are equivalent and you only need to use one or the other.
就您的目的而言,两者是等效的,您只需要使用其中一个即可。
using (StreamWriter file = File.CreateText(@"C:\users\user1.json"))
{
var jsonResult = JsonConvert.SerializeObject(i);
file.WriteLine(jsonResult);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.