Share via


C# Serialize to JSON inside a text file, but the object is empty, why?

Question

Tuesday, May 29, 2018 4:42 PM

Dear All,

The result of my test see below. Does anyone see the cause, why is all empty?

I have created it as described on the link.

Something is missing.
It is a console application, just copy, test it and help me. Thanks in Advance

{"ListChild":[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]}

What is better?
    System.Web.Script.Serialization
      or
   Newtonsoft.Json

With best regards Markus

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

namespace ConsoleApp1
{
    class Program24
    {
        static void Main(string[] args)
        {
            try
            {
                Demo c = new Demo();
                c.Execute();
            }
            catch (Exception ex) { Console.WriteLine(ex.ToString()); }
            Console.WriteLine("Finish, press any key");
            Console.ReadKey();
        }

        internal class Demo
        {
            internal void Execute()
            {
                Master MyMaster = new Master();

                MyMaster.ListChild = new List<Child>();
                MyMaster.ID = 1;
                MyMaster.Info = "Test";
                List<Child> childs = new List<Child>();
                for (int i = 1; i < 100; i++)
                    MyMaster.ListChild.Add(new Child() { ID = i, FK = MyMaster.ID, Info = $"Child {i}" });

                      
                string t1 = JsonConvert.SerializeObject(MyMaster);
                var data = JsonConvert.SerializeObject(MyMaster, Newtonsoft.Json.Formatting.Indented); //, JsonSerializerSettings) ;

                var contentsToWriteToFile = Newtonsoft.Json.JsonConvert.SerializeObject(MyMaster);
                var contentsList = Newtonsoft.Json.JsonConvert.SerializeObject(MyMaster.ListChild);

                
                // use System.Web.Extensions.dll 
                var contentsToWriteToFile3 = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(MyMaster);

                using (StreamWriter writer = new StreamWriter("C:\\__Temp\\Test1.txt", false))
                {
                    writer.Write(contentsToWriteToFile);
                }
            }
        }

        protected static readonly JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore
        };

        internal class Master
        {
            internal int ID { get; set; }
            internal string Info { get; set; }

            [JsonIgnore]
            public string ThisWillNotBeWrittenToTheFile = "because of the [JsonIgnore] attribute.";


            public List<Child> ListChild { get; set; }
        }
        internal class Child
        {
            internal int ID { get; set; }
            internal int FK { get; set; }
            internal string Info { get; set; }
        }
        internal class Result
        {
            internal string MasterInfo { get; set; }
            internal string ChildInfo { get; set; }
        }
    }
}

All replies (3)

Wednesday, May 30, 2018 6:53 AM ✅Answered | 1 vote

Try using public classes and properties.

Or see the usage of DefaultMembersSearchFlags and its replacement:

 


Wednesday, May 30, 2018 5:55 PM ✅Answered | 1 vote

The arrays can be resized using Array.Resize. But it is easier to use List<Child> (which behaves like arrays too).

I think that the classes generated by Paste Special is just a suggestion.


Wednesday, May 30, 2018 4:47 PM

Hi Viorel,

Thanks a lot, so easy, now works.

Do you still have suggestions if I have a JSON file, structure unknown.
How can I quickly generate a matching data model?

I found this feature via clipboard  JSON as class

public class Rootobject
{
    public int ID { get; set; }
    public string Info { get; set; }
    public Listchild[] ListChild { get; set; }
}

public class Listchild
{
    public int ID { get; set; }
    public int FK { get; set; }
    public string Info { get; set; }
}
//Is there a a way to use a list instead a array.  // public Listchild[] ListChild { get; set; }

 Rootobject test = JsonConvert.DeserializeObject<Rootobject>(contentsAsString);
 Works well, but how I can add in a array new items. I must increase the array.
 
In case of add additional child, a list is better. Or have I any possibilities?

Thanks in advance.

With best regards Markus