[c#] Loading a .json file into c# program

I am trying to move my website from XML based config files to JSON based ones. Is there a way to load in a .json file in so that it turns into the object? I have been searching the web and I cannot find one. I already have the .xml file converted and saved as a .json. I would rather not use a 3rd party library.

This question is related to c# json

The answer is


You really should use an established library, such as Newtonsoft.Json (which even Microsoft uses for frameworks such as MVC and WebAPI), or .NET's built-in JavascriptSerializer.

Here's a sample of reading JSON using Newtonsoft.Json:

JObject o1 = JObject.Parse(File.ReadAllText(@"c:\videogames.json"));

// read JSON directly from a file
using (StreamReader file = File.OpenText(@"c:\videogames.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
  JObject o2 = (JObject) JToken.ReadFrom(reader);
}

As mentioned in the other answer I would recommend using json.NET. You can download the package using NuGet. Then to deserialize your json files into C# objects you can do something like;

   JsonSerializer serializer = new JsonSerializer();
   MyObject obj = serializer.Deserialize<MyObject>(File.ReadAllText(@".\path\to\json\config\file.json");

The above code assumes that you have something like

public class MyObject
{
    public string prop1 { get; set; };
    public string prop2 { get; set; };
}

And your json looks like;

{
      "prop1":"value1",
      "prop2":"value2"
}

I prefer using the generic deserialize method which will deserialize json into an object assuming that you provide it with a type who's definition matches the json's. If there are discrepancies between the two it could throw, or not set values, or just ignore things in the json, depends on what the problem is. If the json definition exactly matches the C# types definition then it just works.


Another good way to serialize json into c# is below:

RootObject ro = new RootObject();
     try
    {

        StreamReader sr = new StreamReader(FileLoc);
        string jsonString = sr.ReadToEnd();
        JavaScriptSerializer ser = new JavaScriptSerializer();
        ro = ser.Deserialize<RootObject>(jsonString);


   }

you need to add a reference to system.web.extensions in .net 4.0 this is in program files (x86) > reference assemblies> framework> system.web.extensions.dll and you need to be sure you're using just regular 4.0 framework not 4.0 client


See Microsofts JavaScriptSerializer

The JavaScriptSerializer class is used internally by the asynchronous communication layer to serialize and deserialize the data that is passed between the browser and the Web server. You cannot access that instance of the serializer. However, this class exposes a public API. Therefore, you can use the class when you want to work with JavaScript Object Notation (JSON) in managed code.

Namespace: System.Web.Script.Serialization

Assembly: System.Web.Extensions (in System.Web.Extensions.dll)


I have done it like:

            using (StreamReader sr = File.OpenText(jsonFilePath))
            {
                var myObject = JsonConvert.DeserializeObject<List<YourObject>>(sr.ReadToEnd());
            }

also, you can do this with async call like: sr.ReadToEndAsync(). using Newtonsoft.Json as reference.

Hope, this helps.


Use Server.MapPath to get the actual path of the JSON file and load and read the file using StreamReader

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

public class RootObject
{
    public string url_short { get; set; }
    public string url_long { get; set; }
    public int type { get; set; }
}

public class Program
{
    static public void Main()
    {
       using (StreamReader r = new StreamReader(Server.MapPath("~/test.json")))
       {
           string json = r.ReadToEnd();
           List<RootObject> ro = JsonConvert.DeserializeObject<List<RootObject>>(json);
       }

    Console.WriteLine(ro[0].url_short);                 
    }  
}

Note : Look below link also I have answered for question similar to this.It will be help full for you How to Parse an example string in C#