简体   繁体   English

将JSON文件从磁盘直接反序列化到对象

[英]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. 您可以通过两种方式从文件中反序列化对象。

Solution-1: Read file into a string and deserialize JSON to a type 解决方案1:将文件读入字符串并将JSON反序列化为一种类型

string json = File.ReadAllText(@"c:\myObj.json");
MyObject myObj = JsonConvert.DeserializeObject<MyObject>(json);

Solution-2: Deserialize JSON directly from a file 解决方案2:直接从文件反序列化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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM