C#自定义Json.NET列表序列化

时间:2019-05-08 14:59:01

标签: c# json serialization

我有一个DataObject类的列表:

public class DataObject
    {
        public string Name { get; set; }

        public List<Field> Fields { get; set; }
    }
}



public class Field
{

    public string Name { get; set;}
    public string Type { get; set; }
    public Object Value { get; set; }

    public Field(string name, string type, string value)
    {
        Name = name;
        Type = type;
        if(type == "string") Value = (string)value;
        else Value = Int32.Parse(value);
    }
}

,我想将由DataObject类组成的List序列化为.json文件。我在下面使用Json.NET进行显示的方式中,我尝试了几种情况,但没有找到执行方法。

示例:

Field field1 = new Field("Brand", "string", "Volvo);
Field field2 = new Field("Power", "int", 200);
List<Field> fields = new List<Field>{field1, field2};
DataObject car = new DataObject{
   Name = "Car",
   Fields = list
}
List<DataObjects> objects = new List<DataObjects>{car};

结果:

{
 "Car":{
   "Brand" : "Volvo",
   "Power" : 200
  }
}

1 个答案:

答案 0 :(得分:3)

使用Newtonsoft.Json,序列化非常容易。我接受了您的代码并添加了以下行:

string json = JsonConvert.SerializeObject(objects, Newtonsoft.Json.Formatting.Indented);

它给了我以下输出:

[
  {
    "Name": "Car",
    "Fields": [
      {
        "Name": "Brand",
        "Type": "string",
        "Value": "Volvo"
      },
      {
        "Name": "Power",
        "Type": "int",
        "Value": 200
      }
    ]
  }
]