[英]Deserialise JSON file from disk directly to object
I'm trying to deserialise a JSON file from local disk into an object. 我正在尝试将JSON文件从本地磁盘反序列化为对象。 I've got the following, but this only seems to work when downloading it from the web:
我有以下内容,但这似乎仅在从网络下载时有效:
var client = new HttpClient();
using (var s = await client.GetStreamAsync(filePath))
using (var sr = new StreamReader(s))
using (var jr = new JsonTextReader(sr))
{
var js = new JsonSerializer();
return js.Deserialize<MyObject>(jr);
}
I'm trying to find a way to do this, without first reading it into a string. 我正在尝试找到一种方法,而无需先将其读入字符串。
From Here 从这里
you can deserialize an object from file in two way. 您可以通过两种方式从文件中反序列化对象。
string json = File.ReadAllText(@"c:\myObj.json");
MyObject myObj = JsonConvert.DeserializeObject<MyObject>(json);
using (StreamReader file = File.OpenText(@"c:\myObj.json"))
{
JsonSerializer serializer = new JsonSerializer();
MyObject myObj2 = (MyObject)serializer.Deserialize(file, typeof(MyObject));
}
You can download Newtonsoft.Json from NuGet by following command 您可以通过以下命令从NuGet下载Newtonsoft.Json
Install-Package Newtonsoft.Json
using (var s = new StreamReader(filePath))
{
using (var jr = new JsonTextReader(s))
{
var js = new JsonSerializer();
var obj = js.Deserialize<MyObject>(jr);
return obj;
}
}
You might want to look at this : https://msdn.microsoft.com/en-us/library/bb412179(v=vs.110).aspx 您可能需要看一下: https : //msdn.microsoft.com/zh-cn/library/bb412179(v=vs.110).aspx
It's an MSDN article called "How to: Serialize and Deserialize JSON Data" 这是一条MSDN文章,名为“如何:序列化和反序列化JSON数据”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.