0

I'm trying to deserialise a JSON file from local disk into an object. 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.

Nic
  • 12,220
  • 20
  • 77
  • 105
  • Any reason why you use HttpClient when you're reading from disk? HttpClient seems to only allow http-protocols. – smoksnes Jun 14 '16 at 06:22
  • I tried http://www.newtonsoft.com/json/help/html/performance.htm , and noticed it's not working (as you say). So I was wondering if there is a similar way to do this when reading from disk. – Nic Jun 14 '16 at 06:23
  • Possible duplicate of [How to save/restore serializable object to/from file?](http://stackoverflow.com/questions/6115721/how-to-save-restore-serializable-object-to-from-file) – Ziv Weissman Jun 14 '16 at 06:25
  • Do you have to use HttpClient? Or is it an option to remove it? – smoksnes Jun 14 '16 at 06:26
  • @smoksnes no, don't have to – Nic Jun 14 '16 at 06:27
  • But I guess that the solution needs to be able to handle BOTH http and local disk? – smoksnes Jun 14 '16 at 06:32
  • No, we're only reading/writing our json from/to disk. – Nic Jun 14 '16 at 07:52

3 Answers3

5

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

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

Solution-2: Deserialize JSON directly from a file

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

Install-Package Newtonsoft.Json
Emdadul Sawon
  • 5,730
  • 3
  • 45
  • 48
3
using (var s = new StreamReader(filePath))
{
    using (var jr = new JsonTextReader(s))
    {
        var js = new JsonSerializer();
        var obj = js.Deserialize<MyObject>(jr);
        return obj;
    }
}
smoksnes
  • 10,509
  • 4
  • 49
  • 74
1

You might want to look at this : https://msdn.microsoft.com/en-us/library/bb412179(v=vs.110).aspx

It's an MSDN article called "How to: Serialize and Deserialize JSON Data"

nrocha
  • 384
  • 1
  • 2
  • 9