问题
I want to return a C# class as a JSON object:
This is my code of my switch:
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();
}
}
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);
}
When I return the var o I want to return as this
{"description": "This is a description", "name": "Test1", "values": "[{1 5, 7, 6, 7}]"}
When I return it the object is null.
How can I return the values of the methods into a JSON object?
Can someone point me in the right direction?
Kind regards
回答1:
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 };
}
回答2:
You must define properties or fields to serialize your object. For example :
public class KriDS : IDatasource
{
public string Description { get; set; }
public string Name { get; set; }
public int[] Values { get; set; }
public KriDS()
{
Description = "This is a description";
Name = "Test1";
Values = new int[] { 1, 5, 7, 6, 7 };
}
}
回答3:
if you make your methods static you could assign cosibonding fields to them if you want to.
public class TestObj
{
public String someString = SomeString();
public static String SomeString()
{
return "a String";
}
}
The json searialiser only Serialises fields
来源:https://stackoverflow.com/questions/48182928/how-can-i-return-the-values-from-the-interface-methods-into-a-json-object