0

First off, I'm a garbage C# developer, so don't flame me, but below is what I'm trying to do and a code example of what I'm trying but isn't working.

Goal: Take a model, serialize it into json, write that json to a file on disk.

Model:

namespace My.Dope.Model
{
    [Serializable]
    public class Theme
    {
        [DisplayName("Company Name: ")]
        public string CompanyName { get; set; }


        [DisplayName("Slogan: ")]
        public string Slogan { get; set; }


        [DisplayName("Primary Color: ")]
        public string PrimaryColor { get; set; }


        [DisplayName("Large Logo: ")]
        public HttpPostedFileBase LargeLogo { get; set; }

        [DisplayName("Small Logo: ")]
        public HttpPostedFileBase SmallLogo { get; set; }
    }
}

Some code to maybe serialize it and save it to disk:

using (StreamWriter file = File.CreateText(@"D:\test_theme_json.txt"))
                {
                    JsonSerializer serializer = new JsonSerializer();
                    //serialize object directly into file stream
                    serializer.Serialize(file, theme);
                }

Error:

Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode.

I think it's because of the HttpPostedFileBase items in the model, but I actually don't need those serialized into the JSON file. How can I remove those items, and turn the rest of the model into a .json file that gets saved to the disk?

Thanks for your help!

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
TJBlackman
  • 1,895
  • 3
  • 20
  • 46

2 Answers2

1

I actually don't need those serialized into the JSON file

In JSON.NET there is a [JsonIgnore] attribute that you can decorate properties with.

Related: Newtonsoft ignore attributes?

Strikegently
  • 2,251
  • 20
  • 23
0

To serialize and write it to a file, just do this:

string json = JsonConvert.SerializeObject(theme);
System.IO.File.WriteAllText("yourfile.json", json);
Garrett Vlieger
  • 9,354
  • 4
  • 32
  • 44