JSON - A Newtonsoft example in C#



How to Load an object from disk:


  var path = @"c:\temp\mydata.json.txt";
  
  var contents = File.ReadAllText(path);
  var mydata = JsonConvert.DeserializeObject<MyData>(contents);
  

How to Save an object to disk:


  var path = @"c:\temp\mydata.json.txt";
  
  var mydata = new MyData();
  var contents = JsonConvert.SerializeObject(mydata, Formatting.Indented);
  File.WriteAllText(path, contents);
  

A JSON text file:


  {
      "title": "json - a Newtonsoft example in C#",
      "description": "A zuga.net article",
      "type": "article"
  }
  

A JSON class:


  using Newtonsoft.Json;
  using System;
  
  namespace test1
  {
      class MyData
      {
          [JsonProperty("title", Order = 1)]
          public string title = "";
  
          [JsonProperty("description", Order = 2)]
          public string description = "";
  
          [JsonProperty("type", Order = 3)]
          public string type = "";
      }
  }
  

In this example, the JsonProperty attributes are optional since we are specifying the default behaviour, but if you need to change a field name, or the order in which they are written, this is how.


Installing JSON:

You install Newtonsoft JSON using the NuGet Package Manager.


Visual Studio ... Manage Nuget Packages ... (search for) ... Json.NET

or

Visual Studio ... View ... Other Windows ... Package Manager Console


  PM> Install-Package Newtonsoft.Json
  

  Installing 'Newtonsoft.Json 10.0.3'.
  Successfully installed 'Newtonsoft.Json 10.0.3'.
  Adding 'Newtonsoft.Json 10.0.3' to testproject1.
  Successfully added 'Newtonsoft.Json 10.0.3' to testproject1.
  Uninstalling 'Newtonsoft.Json 5.0.4'.
  Successfully uninstalled 'Newtonsoft.Json 5.0.4'.
  

Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath