我有一些内部属性的类,我想将它们序列化为json.我怎么能做到这一点?例如
public class Foo
{
    internal int num1 { get; set; }
    internal double num2 { get; set; }
    public string Description { get; set; }
    public override string ToString()
    {
        if (!string.IsNullOrEmpty(Description))
            return Description;
        return base.ToString();
    }
}
使用保存它
Foo f = new Foo();
f.Description = "Foo Example";
JsonSerializerSettings settings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All };
 string jsonOutput = JsonConvert.SerializeObject(f, Formatting.Indented, settings);
 using (StreamWriter sw = new StreamWriter("json_file.json"))
 {
     sw.WriteLine(jsonOutput);
 }
我明白了
{  
"$type": "SideSlopeTest.Foo, SideSlopeTest",
"Description": …所以,我有一个自定义类'User',如下所示:
class User
    {
        string firstname;
        string lastname;
        string proposedname;
        public User(string firstname, string lastname)
        {
            this.firstname = firstname;
            this.lastname = lastname;
            this.proposedname = $"{firstname}.{lastname}".ToLower();
        }
}
另一个类"UserCreator有一个方法"GenerateList"和一个方法"WriteList"以及一个简单的List字段:
public class UserCreator
    {
        internal List<User> Users;
        public UserCreator(int n = 1000)
        {
            Users = new List<User>();
            this.GenerateList(n);
        }
       public  void WriteList(string outputPath)
        {
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(this.Users, Newtonsoft.Json.Formatting.Indented);
            System.IO.File.WriteAllText(outputPath, json);
        }
        void GenerateList(int amount)
        {
            List<User> result = new List<User>();
            ///...
            this.Users = result;
        }
    }
一切正常,直到它到达WriteList()中的Serialization部分.而不是像预期的那样工作我得到这样的东西:
[
  {},
  {},
  {}, …