Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法将FileStream隐式转换为Json文件的StreamWriter_C#_.net Core - Fatal编程技术网

C# 无法将FileStream隐式转换为Json文件的StreamWriter

C# 无法将FileStream隐式转换为Json文件的StreamWriter,c#,.net-core,C#,.net Core,所以,我正在读一本关于.NETCore3的书,我正在学习如何序列化JSON文件。我遇到了一个类型问题,我还没有找到解决方案。我尝试过解决这个问题,但后来我遇到了其他类型的问题。下面代码的问题是在File.Create(jsonPath)中Main的最后一个using语句中的CS0029: 无法将类型“System.IO.FileStream”隐式转换为“System.IO.StreamWriter” 根据我从Microsoft文档中获得的示例,我尝试将using语句更改为使用FileStream

所以,我正在读一本关于.NETCore3的书,我正在学习如何序列化JSON文件。我遇到了一个类型问题,我还没有找到解决方案。我尝试过解决这个问题,但后来我遇到了其他类型的问题。下面代码的问题是在
File.Create(jsonPath)
中Main的最后一个using语句中的CS0029:

无法将类型“System.IO.FileStream”隐式转换为“System.IO.StreamWriter”

根据我从Microsoft文档中获得的示例,我尝试将using语句更改为使用FileStream类型而不是StreamWriter,但这在
jsonSerializer.Serialize(jsonStream,people)
行的jsonStream变量处产生了一个错误,该行显示:

无法从“System.IO.FileStream”转换为“System.IO.TextWriter”

代码如下:

using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.IO;
using Packt.Shared;
using static System.Console;
using static System.Environment;
using static System.IO.Path;

namespace WorkingWithSerialization
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Person> people = new List<Person>
            {
                new Person(30000M)
                {
                    FirstName = "Adam",
                    LastName = "Smith",
                    DateOfBirth = new DateTime(1756,12,12)
                },
                new Person(40000M)
                {
                    FirstName = "Lisa",
                    LastName = "Simpson",
                    DateOfBirth = new DateTime(1980,4,30)
                },
                new Person(20000M)
                {
                    FirstName = "Barney",
                    LastName = "Rubble",
                    DateOfBirth = new DateTime(1962,7,14),
                    Children = new HashSet<Person>
                    {
                        new Person(0M)
                        {
                            FirstName = "Bob",
                            LastName = "Rubble",
                            DateOfBirth = new DateTime(1986,5,3)
                        },
                        new Person(0M)
                        {
                            FirstName = "Bamm-Bamm",
                            LastName = "Rubble",
                            DateOfBirth = new DateTime(1984,3,15)
                        }
                    }
                }
            };

            XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Person>));
            string path = Combine(CurrentDirectory, "people.xml");
            using(FileStream stream = File.Create(path))
            {
                xmlSerializer.Serialize(stream,people);
            }
            WriteLine($"Wrote {new FileInfo(path).Length} bytes to {path}.");
            WriteLine($"\n{File.ReadAllText(path)}");

            using(FileStream xmlLoad = File.Open(path, FileMode.Open))
            {
                List<Person> loadedPeople = (List<Person>)xmlSerializer.Deserialize(xmlLoad);
                foreach(Person person in loadedPeople)
                {
                    WriteLine($"{person.FirstName} has {person.Children.Count} children.");
                }
            }

            string jsonPath = Combine(CurrentDirectory, "people.json");
            using(StreamWriter jsonStream = File.Create(jsonPath))
            {
                var jsonSerializer = new Newtonsoft.Json.JsonSerializer();
                jsonSerializer.Serialize(jsonStream, people);
            }
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Xml.Serialization;
使用System.IO;
使用Packt.Shared;
使用静态系统控制台;
使用静态系统。环境;
使用静态System.IO.Path;
名称空间工作与序列化
{
班级计划
{
静态void Main(字符串[]参数)
{
列出人员=新列表
{
新人(30000M)
{
FirstName=“亚当”,
LastName=“史密斯”,
DateOfBirth=新日期时间(1756,12,12)
},
新增人员(40000M)
{
FirstName=“Lisa”,
LastName=“辛普森”,
DateOfBirth=新日期时间(1980,4,30)
},
新人(20000M)
{
FirstName=“Barney”,
LastName=“碎石”,
DateOfBirth=新的日期时间(1962,7,14),
Children=新哈希集
{
新人(百万)
{
FirstName=“Bob”,
LastName=“碎石”,
DateOfBirth=新日期时间(1986,5,3)
},
新人(百万)
{
FirstName=“Bamm-Bamm”,
LastName=“碎石”,
DateOfBirth=新日期时间(1984,3,15)
}
}
}
};
XmlSerializer XmlSerializer=新的XmlSerializer(typeof(List));
string path=Combine(CurrentDirectory,“people.xml”);
使用(FileStream-stream=File.Create(path))
{
序列化(流,人);
}
WriteLine($“将{new FileInfo(path).Length}字节写入{path}”);
WriteLine($“\n{File.ReadAllText(path)}”);
使用(FileStream xmlLoad=File.Open(路径,FileMode.Open))
{
List loadedPeople=(List)xmlSerializer.Deserialize(xmlLoad);
foreach(已加载人员中的人员)
{
WriteLine($“{person.FirstName}有{person.Children.Count}个孩子。”);
}
}
字符串jsonPath=Combine(CurrentDirectory,“people.json”);
使用(StreamWriter jsonStream=File.Create(jsonPath))
{
var jsonSerializer=newnewtonsoft.Json.jsonSerializer();
序列化(jsonStream,people);
}
}
}
}
我还在.csproj文件中包含了最新版本的Newtonsoft.Json,但我认为这不是问题所在


我也尝试过不同的铸造方法,但没有任何积极的结果。我不确定我做错了什么。

您可以使用此JSONHelpers

public static class JsonHelpers
{
    public static T CreateFromJsonStream<T>(this Stream stream)
    {
        JsonSerializer serializer = new JsonSerializer();
        T data;
        using (StreamReader streamReader = new StreamReader(stream))
        {
            data = (T)serializer.Deserialize(streamReader, typeof(T));
        }
        return data;
    }

    public static T CreateFromJsonString<T>(this String json)
    {
        T data;
        using (MemoryStream stream = new MemoryStream(System.Text.Encoding.Default.GetBytes(json)))
        {
            data = CreateFromJsonStream<T>(stream);
        }
        return data;
    }

    public static T CreateFromJsonFile<T>(this String fileName)
    {
        T data;
        using (FileStream fileStream = new FileStream(fileName, FileMode.Open))
        {
            data = CreateFromJsonStream<T>(fileStream);
        }
        return data;
    }
}
公共静态类JsonHelpers
{
公共静态T CreateFromJsonStream(此流)
{
JsonSerializer serializer=新的JsonSerializer();
T数据;
使用(StreamReader StreamReader=新StreamReader(stream))
{
数据=(T)序列化程序。反序列化(streamReader,typeof(T));
}
返回数据;
}
公共静态T CreateFromJsonString(此字符串为json)
{
T数据;
使用(MemoryStream stream=newmemoryStream(System.Text.Encoding.Default.GetBytes(json)))
{
数据=CreateFromJsonStream(流);
}
返回数据;
}
公共静态T CreateFromJsonFile(此字符串文件名)
{
T数据;
使用(FileStream FileStream=newfilestream(fileName,FileMode.Open))
{
data=CreateFromJsonStream(fileStream);
}
返回数据;
}
}
请查看此以获取详细解释。
您可以使用这些扩展方法将流转换为JSON字符串

您需要额外的步骤来创建使用
文件流的
StreamWriter

string jsonPath = Combine(CurrentDirectory, "people.json");
using (FileStream fs = File.Create(jsonPath))
using (StreamWriter jsonStream = new StreamWriter(fs))
{
    var jsonSerializer = new Newtonsoft.Json.JsonSerializer();
    jsonSerializer.Serialize(jsonStream, people);
}
如果我创建一个最小的Person类来编译代码,我会得到一个json文件,如下所示:

[{
        "FirstName": "Adam",
        "LastName": "Smith",
        "DateOfBirth": "1756-12-12T00:00:00",
        "Children": null
    }, {
        "FirstName": "Lisa",
        "LastName": "Simpson",
        "DateOfBirth": "1980-04-30T00:00:00",
        "Children": null
    }, {
        "FirstName": "Barney",
        "LastName": "Rubble",
        "DateOfBirth": "1962-07-14T00:00:00",
        "Children": [{
                "FirstName": "Bob",
                "LastName": "Rubble",
                "DateOfBirth": "1986-05-03T00:00:00",
                "Children": null
            }, {
                "FirstName": "Bamm-Bamm",
                "LastName": "Rubble",
                "DateOfBirth": "1984-03-15T00:00:00",
                "Children": null
            }
        ]
    }
]

谢谢你,@Nainesh。明天我会看看这些,看看是否有用。非常感谢。现在它有意义了。我现在要更新我的答案。对不起-这似乎有利于反序列化JSON文件中的数据,但我的做法正好相反。我试图创建一个JSON文件,然后将数据序列化为JSON格式并将其写入该文件。不过还是要谢谢你,我以后可能会用到这个。非常感谢你!我马上就要试试这个!这正是我所需要的。现在我看到了它,这是有意义的,因为我看到我可以传递一个流类型来创建StreamWriter,而FileStream从流继承。