如何将接口方法中的值返回到JSON对象? [英] How can I return the values from the interface methods into a JSON object?
本文介绍了如何将接口方法中的值返回到JSON对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将C#类作为JSON对象返回:
I want to return a C# class as a JSON object:
这是我的开关代码:
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
这是它的样子:
For each type it must return a whole class. Let's take for example type is KRI
and it must return the class KriDS
this is how it looks like:
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;
}
}
在我的控制器中,我使用以下方法:
And in my controller I use the following method:
[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 $ c时$ c>我想以此返回
{"description": "This is a description", "name": "Test1", "values": "[{1 5, 7, 6, 7}]"}
当我返回它时,对象为空。
When I return it the object is null.
如何将方法的值返回到JSON对象?
How can I return the values of the methods into a JSON object?
有人能指出我正确的方向吗?
Can someone point me in the right direction?
亲切的问候
推荐答案
而不是创建字段所需的方法/属性。方法可以填充这些。尝试使用此:
Instead of methods you need to create fields/properties. Methods can populate those. Try using this:
public class KriDS : IDatasource
{
public string description = "This is a description";
public string name = "Test1";
public int[] values = new int[] { 1, 5, 7, 6, 7 };
}
这篇关于如何将接口方法中的值返回到JSON对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文