Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Read and write JSON in c# WinForms

Read and write JSON in c# WinForms

Scheduled Pinned Locked Moved C#
csharpmongodbasp-netdotnetvisual-studio
9 Posts 4 Posters 1 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J Offline
    J Offline
    jkirkerx
    wrote on last edited by
    #1

    I wanted to mimic .net core and use an appSettings.Json file, well it didn't work out. Guess .Net Core Extensions won't work in my project. So I wrote some code using Newtonsoft, could not read the file and parse out pure JSON. Well I was able to read the file but not able to deserialize it. Searched the internet and found a couple of solutions that didn't pan out as well. So I searching for a NuGet package and found one, but no documentation. Anybody used or found a package that they like? I just want to read and write my MongoDB connection string. Side Note, really liking Mongo for this project! except for this part. But I got some automated code to load and program Mongo going now, just need to finish this up.

    If it ain't broke don't fix it Discover my world at jkirkerx.com

    OriginalGriffO M Richard DeemingR J 5 Replies Last reply
    0
    • J jkirkerx

      I wanted to mimic .net core and use an appSettings.Json file, well it didn't work out. Guess .Net Core Extensions won't work in my project. So I wrote some code using Newtonsoft, could not read the file and parse out pure JSON. Well I was able to read the file but not able to deserialize it. Searched the internet and found a couple of solutions that didn't pan out as well. So I searching for a NuGet package and found one, but no documentation. Anybody used or found a package that they like? I just want to read and write my MongoDB connection string. Side Note, really liking Mongo for this project! except for this part. But I got some automated code to load and program Mongo going now, just need to finish this up.

      If it ain't broke don't fix it Discover my world at jkirkerx.com

      OriginalGriffO Offline
      OriginalGriffO Offline
      OriginalGriff
      wrote on last edited by
      #2

      Newtonsoft works for me:

              string strConnect = "my connection string";
              string json = Newtonsoft.Json.JsonConvert.SerializeObject(strConnect);
      

      ...
      string readback = Newtonsoft.Json.JsonConvert.DeserializeObject(json);

      It doesn't have to be a string, it can be any class instance! So a "Settings" class that includes your connection information maybe? Or a list of Settings objects?

              List readback = Newtonsoft.Json.JsonConvert.DeserializeObject\>(json);
      

      The world is the mollusc of your choice!

      Sent from my Amstrad PC 1640 Never throw anything away, Griff Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

      "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
      "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

      J 1 Reply Last reply
      0
      • J jkirkerx

        I wanted to mimic .net core and use an appSettings.Json file, well it didn't work out. Guess .Net Core Extensions won't work in my project. So I wrote some code using Newtonsoft, could not read the file and parse out pure JSON. Well I was able to read the file but not able to deserialize it. Searched the internet and found a couple of solutions that didn't pan out as well. So I searching for a NuGet package and found one, but no documentation. Anybody used or found a package that they like? I just want to read and write my MongoDB connection string. Side Note, really liking Mongo for this project! except for this part. But I got some automated code to load and program Mongo going now, just need to finish this up.

        If it ain't broke don't fix it Discover my world at jkirkerx.com

        M Offline
        M Offline
        Mc_Topaz
        wrote on last edited by
        #3

        I'm not sure this will help, but why not use the built-in JSON package in .NET-framework 4.0 or later? For instance try this: 1) Create a new console application. 2) Add a reference to System.Web.Extensions.dll. 3) Paste the following code:

        using System;
        using System.Collections.Generic;
        using System.Web.Script.Serialization;

        namespace ConsoleApplication1
        {
        class Program
        {
        static void Main(string[] args)
        {
        var list = new List();
        list.Add(new Person() { Name = "Dude", Age = 21 });
        list.Add(new Person() { Name = "Chap", Age = 28 });

                var json = new JavaScriptSerializer();
                var result = json.Serialize(list);
                var listFromJson = json.Deserialize(result, typeof(List)) as List;
            }
        }
        
        class Person
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }
        

        }

        Just debug and step through the code to verify it works :) I have serialized and deserialized a List with a custom class. You can of course serialize/deserialize whatever you want. Best regards, /Steffe

        J 1 Reply Last reply
        0
        • J jkirkerx

          I wanted to mimic .net core and use an appSettings.Json file, well it didn't work out. Guess .Net Core Extensions won't work in my project. So I wrote some code using Newtonsoft, could not read the file and parse out pure JSON. Well I was able to read the file but not able to deserialize it. Searched the internet and found a couple of solutions that didn't pan out as well. So I searching for a NuGet package and found one, but no documentation. Anybody used or found a package that they like? I just want to read and write my MongoDB connection string. Side Note, really liking Mongo for this project! except for this part. But I got some automated code to load and program Mongo going now, just need to finish this up.

          If it ain't broke don't fix it Discover my world at jkirkerx.com

          Richard DeemingR Offline
          Richard DeemingR Offline
          Richard Deeming
          wrote on last edited by
          #4

          Using .NET Core Configuration with legacy projects - Ben Foster[^]


          "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

          "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

          J 1 Reply Last reply
          0
          • M Mc_Topaz

            I'm not sure this will help, but why not use the built-in JSON package in .NET-framework 4.0 or later? For instance try this: 1) Create a new console application. 2) Add a reference to System.Web.Extensions.dll. 3) Paste the following code:

            using System;
            using System.Collections.Generic;
            using System.Web.Script.Serialization;

            namespace ConsoleApplication1
            {
            class Program
            {
            static void Main(string[] args)
            {
            var list = new List();
            list.Add(new Person() { Name = "Dude", Age = 21 });
            list.Add(new Person() { Name = "Chap", Age = 28 });

                    var json = new JavaScriptSerializer();
                    var result = json.Serialize(list);
                    var listFromJson = json.Deserialize(result, typeof(List)) as List;
                }
            }
            
            class Person
            {
                public string Name { get; set; }
                public int Age { get; set; }
            }
            

            }

            Just debug and step through the code to verify it works :) I have serialized and deserialized a List with a custom class. You can of course serialize/deserialize whatever you want. Best regards, /Steffe

            J Offline
            J Offline
            jkirkerx
            wrote on last edited by
            #5

            I saw a couple examples of that while searching, but passed on it because I had already written code.

            If it ain't broke don't fix it Discover my world at jkirkerx.com

            1 Reply Last reply
            0
            • OriginalGriffO OriginalGriff

              Newtonsoft works for me:

                      string strConnect = "my connection string";
                      string json = Newtonsoft.Json.JsonConvert.SerializeObject(strConnect);
              

              ...
              string readback = Newtonsoft.Json.JsonConvert.DeserializeObject(json);

              It doesn't have to be a string, it can be any class instance! So a "Settings" class that includes your connection information maybe? Or a list of Settings objects?

                      List readback = Newtonsoft.Json.JsonConvert.DeserializeObject\>(json);
              

              The world is the mollusc of your choice!

              Sent from my Amstrad PC 1640 Never throw anything away, Griff Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

              J Offline
              J Offline
              jkirkerx
              wrote on last edited by
              #6

              I've been working with Newtonsoft this morning and still can't deserialize. hmm... I'll post my code

              If it ain't broke don't fix it Discover my world at jkirkerx.com

              1 Reply Last reply
              0
              • J jkirkerx

                I wanted to mimic .net core and use an appSettings.Json file, well it didn't work out. Guess .Net Core Extensions won't work in my project. So I wrote some code using Newtonsoft, could not read the file and parse out pure JSON. Well I was able to read the file but not able to deserialize it. Searched the internet and found a couple of solutions that didn't pan out as well. So I searching for a NuGet package and found one, but no documentation. Anybody used or found a package that they like? I just want to read and write my MongoDB connection string. Side Note, really liking Mongo for this project! except for this part. But I got some automated code to load and program Mongo going now, just need to finish this up.

                If it ain't broke don't fix it Discover my world at jkirkerx.com

                J Offline
                J Offline
                jkirkerx
                wrote on last edited by
                #7

                I'm completely missing something here. This should work! But var settings is always null. Settings Wireless.Models.Settings DbConnection = null SmtpConnection = null My json file: IN the project folder, marked as Content, Copy if newer

                {
                "Settings": {
                "DbConnection": {
                "Connection": "mongodb://admin:Password@localhost",
                "Database": "database"
                },
                "SmtpConnection": {
                "Server": "smtp.gmail.com",
                "User": "emailAddress",
                "Pass": "password",
                "Port": "587",
                "SSL": "True"
                }
                }
                }

                My Model, I double checked it to make sure it matches

                public class Settings
                {
                public MongoDbConfig DbConnection { get; set; }
                public SmtpConfig SmtpConnection { get; set; }
                }

                public class MongoDbConfig
                {
                    public string Connection { get; set; }
                    public string Database { get; set; }
                }
                
                public class SmtpConfig
                {
                    public string Server { get; set; }
                    public string User { get; set; }
                    public string Pass { get; set; }
                    public int Port { get; set; }
                    public bool SSL { get; set; }
                }
                

                My function to read the file, I verified the file in jsonText

                public static void GetSettings()
                {
                var appPath = Path.Combine(Application.StartupPath, "appSettings.json");
                var jsonText = File.ReadAllText(appPath);
                var settings = JsonConvert.DeserializeObject(jsonText);
                Console.Write(appPath);
                }

                jsonText output

                jsonText = "{\r\n \"Settings\": {\r\n \"DbConnection\": {\r\n \"Connection\": \"mongodb://admin:Password@localhost\",\r\n \"Database\": \"wirelessDb\"\r\n },\r\n \"SmtpConnection\": {\r\n \"Server\": \"smtp.gmail.com\",\r\n

                If it ain't broke don't fix it Discover my world at jkirkerx.com

                1 Reply Last reply
                0
                • Richard DeemingR Richard Deeming

                  Using .NET Core Configuration with legacy projects - Ben Foster[^]


                  "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                  J Offline
                  J Offline
                  jkirkerx
                  wrote on last edited by
                  #8

                  I took a look at the link and gave it a try, and was able to load the example, but not able to figure out how to use the object.

                  If it ain't broke don't fix it Discover my world at jkirkerx.com

                  1 Reply Last reply
                  0
                  • J jkirkerx

                    I wanted to mimic .net core and use an appSettings.Json file, well it didn't work out. Guess .Net Core Extensions won't work in my project. So I wrote some code using Newtonsoft, could not read the file and parse out pure JSON. Well I was able to read the file but not able to deserialize it. Searched the internet and found a couple of solutions that didn't pan out as well. So I searching for a NuGet package and found one, but no documentation. Anybody used or found a package that they like? I just want to read and write my MongoDB connection string. Side Note, really liking Mongo for this project! except for this part. But I got some automated code to load and program Mongo going now, just need to finish this up.

                    If it ain't broke don't fix it Discover my world at jkirkerx.com

                    J Offline
                    J Offline
                    jkirkerx
                    wrote on last edited by
                    #9

                    Searched for complex deserialization, and ran across this website [json2csharp - generate c# classes from json](http://json2csharp.com/) and code to deserialize New Model

                    public class DbConnection
                    {
                    public string Connection { get; set; }
                    public string Database { get; set; }
                    }

                    public class SmtpConnection
                    {
                    public string Server { get; set; }
                    public string User { get; set; }
                    public string Pass { get; set; }
                    public string Port { get; set; }
                    public string SSL { get; set; }
                    }

                    public class Settings
                    {
                    public DbConnection DbConnection { get; set; }
                    public SmtpConnection SmtpConnection { get; set; }
                    }

                    public class RootObject
                    {
                    public Settings Settings { get; set; }
                    }

                    Code to deserialize

                    JavaScriptSerializer oJS = new JavaScriptSerializer();
                    RootObject oRootObject = new RootObject();
                    oRootObject = oJS.Deserialize(jsonText);

                    If it ain't broke don't fix it Discover my world at jkirkerx.com

                    1 Reply Last reply
                    0
                    Reply
                    • Reply as topic
                    Log in to reply
                    • Oldest to Newest
                    • Newest to Oldest
                    • Most Votes


                    • Login

                    • Don't have an account? Register

                    • Login or register to search.
                    • First post
                      Last post
                    0
                    • Categories
                    • Recent
                    • Tags
                    • Popular
                    • World
                    • Users
                    • Groups