58

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.

5
  • Possible duplicate? See stackoverflow.com/questions/4521239/… Commented Aug 30, 2013 at 17:29
  • 8
    I have been searching the web and I cannot find one hard to believe... Commented Aug 30, 2013 at 17:36
  • fair enough, I found some of this similar stuff but I tried their solutions and it was not working. Making some progress now Commented Aug 30, 2013 at 17:41
  • Possible duplicate of Read and parse a Json File in C# Commented Oct 14, 2016 at 2:03
  • 2
    json.net is the universally used c# json library Commented Jul 18, 2017 at 19:06

6 Answers 6

97

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);
}
Sign up to request clarification or add additional context in comments.

7 Comments

Well...obviuosly the OP shouldn't write his own. But if he wants a framework class that implements this functionality, JavaScriptSerializer would work.
I had downloaded NewtonSoft but didnt want someone yelling at me for using an outside library
@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.
@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<T>(string rawJson) method? Also, you can use File.ReadAllText(string filepath) to simplify the file IO.
If your json file contains an array you will need to change JObject to JArray
|
11

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

2 Comments

don't forget sr.Close();
Where do I get RootObject from? I tried including System.Xaml
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.

2 Comments

missing a closing ) paren on the second line.
There was no Deserialize method taking a string, when I tried to build it.
5

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.

Comments

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#

2 Comments

What is Server?
@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 stackoverflow.com/questions/49398965/… for more details
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)

1 Comment

JSON is (contrary to popular belief) not a subset of Javascript, see for example medium.com/joys-of-javascript/json-js-42a28471221d

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.