我有一个班级,
public class Parameters
{
public int Id {get;set;}
public string FilterParam {get;set;}
public string NameParam {get;set;}
public IList<int> CollectionsIds {get;set;}
public DataTable ParamTable {get;set;}
}
当我尝试序列化为JSON时,我得到循环引用错误“序列化对象时检测到循环引用”。
我的序列化代码是:
JSONSerializer.SerializeObject<Parameters>(parameters)
private static JavaScriptSerializer _jsonSerializer = null;
private static JavaScriptSerializer JSONSerializer
{
get
{
if (_jsonSerializer == null)
{
_jsonSerializer = new JavaScriptSerializer();
_jsonSerializer.MaxJsonLength = 999999999;
}
return _jsonSerializer;
}
}
public static string SerializeObject<T>(T obj)
{
return JSONSerializer.Serialize(obj);
}
如果类包含dataTable,如何将类序列化为JSON格式?
注意:如果我将dataTable设置为null它可以正常工作,但每当我尝试填充dataTable并调用方法来序列化它就会失败。
答案 0 :(得分:1)
只需添加一个字段(字典列表)即可将DataTable
假冒到您的班级。并忽略DataTable
成员。然后,您可以根据需要序列化此类的对象。
public class Parameters
{
public int Id {get;set;}
public string FilterParam {get;set;}
public string NameParam {get;set;}
public IList<int> CollectionsIds {get;set;}
[ScriptIgnore]
public DataTable ParamTable {get;set;}
public List<Dictionary<string, object>> _fakeParamTable
{
get
{
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach ( DataRow dr in ParamTable .Rows )
{
row = new Dictionary<string, object>();
foreach ( DataColumn col in dt.Columns )
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return rows;
}
}
}
答案 1 :(得分:0)
使用此库:https://www.nuget.org/packages/newtonsoft.json/
这个JSON:
{
Parameters :
{
id: 1,
FilterParam: "2",
NameParam: "2",
CollectionsIds: [1,2,3,1],
ParamTable: {id:1,name:2,code:"3"}
}
}
将有课程(http://json2csharp.com/):
P
ublic class ParamTable
{
public int id { get; set; }
public int name { get; set; }
public string code { get; set; }
}
public class Parameters
{
public int id { get; set; }
public string FilterParam { get; set; }
public string NameParam { get; set; }
public List<int> CollectionsIds { get; set; }
public ParamTable ParamTable { get; set; }
}
public class RootObject
{
public Parameters Parameters { get; set; }
}
所以你会siple序列化,你想要的是这样的:
JsonConvert.DeserializeObject<RootObject>(myJSON);