57

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.

Dale K
  • 25,246
  • 15
  • 42
  • 71
ford prefect
  • 7,096
  • 11
  • 56
  • 83

6 Answers6

95

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);
}
STW
  • 44,917
  • 17
  • 105
  • 161
  • 2
    Well...obviuosly the OP shouldn't *write his own*. But if he wants a framework class that implements this functionality, [`JavaScriptSerializer`](http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx) would work. – Kirk Woll Aug 30 '13 at 17:34
  • I had downloaded NewtonSoft but didnt want someone yelling at me for using an outside library – ford prefect Aug 30 '13 at 17:46
  • @inquisitiveIdiot I misunderstood and thought you intended to write your own. The built in JavascriptSerializer is decent for most use cases, but Newtonsoft is very fast and full featured. – STW Aug 30 '13 at 17:51
  • 3
    @inquisitiveIdiot I prefer Newtonsoft's implementation to any others. Just gonna point out I'm not a fan of the use in your sample code. Why treat this dynamically when you can use the simpler, cleaner, more type safe `Deserialize(string rawJson)` method? Also, you can use `File.ReadAllText(string filepath)` to simplify the file IO. – evanmcdonnal Aug 30 '13 at 18:13
  • Good point, I grabbed that sample straight from their doc on "how to read a JSON file from disk". – STW Aug 30 '13 at 18:14
  • @fordprefect From what I've seen, people are more likely to yell about trying to roll your own, but for specific things, mostly parsers like JSON or HTML, but encryption is also often mentioned. – htmlcoderexe Apr 27 '17 at 22:34
  • 1
    If your json file contains an array you will need to change JObject to JArray – Rider Harrison Sep 22 '21 at 13:31
12

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

ford prefect
  • 7,096
  • 11
  • 56
  • 83
10

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.

evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115
4

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#

Community
  • 1
  • 1
Shakir Ahamed
  • 1,290
  • 3
  • 16
  • 39
  • 1
    What is Server? – MAESTRO_DE May 08 '20 at 09:24
  • @MAESTRO_DE Incase you're using .net core, you should use IHostingEnvironment (net core 2.2) or IWebHostEnvironment (net core 3.0) instead. Please refer https://stackoverflow.com/questions/49398965/what-is-the-equivalent-of-server-mappath-in-asp-net-core for more details – Anh Hoang Nov 30 '20 at 04:19
4

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.

Deepak Shaw
  • 461
  • 3
  • 6
1

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)

Seth Flowers
  • 8,990
  • 2
  • 29
  • 42
  • 1
    JSON is (contrary to popular belief) *not* a subset of Javascript, see for example https://medium.com/joys-of-javascript/json-js-42a28471221d – Nubok Jun 08 '16 at 21:14