【发布时间】:2018-01-10 08:13:20
【问题描述】:
我想将 C# 类作为 JSON 对象返回:
这是我的开关代码:
public IDatasource GetDataSource(DataSourceType type)
{
switch (type)
{
case DataSourceType.CONTROL:
return new ControlDS();
case DataSourceType.RISK:
return new RiskDS();
case DataSourceType.MOI:
return new MoiDS();
case DataSourceType.LOSSEVENTS:
return new LossEventDS();
case DataSourceType.KRI:
return new KriDS();
default:
throw new ArgumentOutOfRangeException();
}
}
对于每种类型,它必须返回一个完整的类。让我们以类型为KRI 为例,它必须返回类KriDS 这是它的样子:
public class KriDS : IDatasource
{
public string Description()
{
var description = "This is a description";
return description;
}
public string Name()
{
var kriname = "Test1";
return kriname;
}
public int[] Values()
{
int[] values = new int[] { 1, 5, 7, 6, 7 };
return values;
}
}
在我的控制器中,我使用以下方法:
[HttpGet]
public string GetDataSource(string id)
{
// var type = (DataSourceType)id;
DataSourceType type;
if(!Enum.TryParse(id, out type))
{
throw new ArgumentOutOfRangeException();
}
var o = _dashboarBusiness.GetDataSource(type = DataSourceType.KRI);
return Newtonsoft.Json.JsonConvert.SerializeObject(o);
}
当我返回 var o 时,我想这样返回
{"description": "This is a description", "name": "Test1", "values": "[{1 5, 7, 6, 7}]"}
当我返回它时,对象为空。
如何将方法的值返回到 JSON 对象中?
有人能指出我正确的方向吗?
亲切的问候
【问题讨论】:
-
你需要使用字段/属性而不是方法。
-
是的,你不能序列化方法,用属性或字段替换它们。
-
并且不要自己序列化为 JSON。让框架来做。只需返回对象。