相关疑难解决方法(0)

具有内部属性的JSON Serializer对象

我有一些内部属性的类,我想将它们序列化为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();
    }
}
Run Code Online (Sandbox Code Playgroud)

使用保存它

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);
 }
Run Code Online (Sandbox Code Playgroud)

我明白了

{  
"$type": "SideSlopeTest.Foo, SideSlopeTest",
"Description": …
Run Code Online (Sandbox Code Playgroud)

.net c# json

15
推荐指数
1
解决办法
1万
查看次数

C#:List <CustomClass>的JSON序列化返回空数组?

所以,我有一个自定义类'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();
        }
}
Run Code Online (Sandbox Code Playgroud)

另一个类"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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

一切正常,直到它到达WriteList()中的Serialization部分.而不是像预期的那样工作我得到这样的东西:

[
  {},
  {},
  {}, …
Run Code Online (Sandbox Code Playgroud)

c# json.net

2
推荐指数
1
解决办法
77
查看次数

标签 统计

c# ×2

.net ×1

json ×1

json.net ×1