C# Json 组合了两个不同的对象



我需要有这种格式的json(当数据为空时,只需检索时间字段):

var chartData = [
            {
                "time": "0",
                "value": -0.307
            },
            {
                "time": "1",
                "value": -0.168
            },
            {
                "time": "2"
            },
            {
                "time": "3",
                "value": -0.027
            }
]

我创建了两个类:

  • 数据V1(时间)
  • dataV2(时间,值 -> 应为双精度)

法典:

public class dataV1
{
    public string time { get; set; }
    public dataV1(string Ptime)
    {
        this.time = Ptime;      
    }
    public dataV1() { }
}
public class dataV2
{
    public string time { get; set; }
    public double value { get; set; }
    public dataV2(string Ptime, double Pvalue)
    {
        this.time = Ptime;   
        this.value = Pvalue;   
    }
    public dataV2() { }
}

然后在 C# sql 中:

if (sqlReader["value"] != DBNull.Value) 

如何组合这两个类并在值为空时使用dataV1,当我们的值不为空时使用 dataV2

并检索 JSON 结果

return Json(new
{
    chartData,
}, JsonRequestBehavior.AllowGet);
你可以

让你的dataV2类(我建议将其名称更改为更有意义的名称)有一个double?可为空的字段,而不是一个double。这样,对于 JSON 中有"值"字段的情况,您就不必复制对象:

public class SomeData
{
    public string Time { get; set; }
    public double? Value { get; set; }
    public SomeData(string time, double? value)
    {
        this.time = time;   
        this.value = value;   
    }
    public SomeData() { }
}

然后反序列化它:

SomeData data = JsonConvert.DeserializeObject<SomeData>(json, 
                            new JsonSerializerSettings 
                            { NullValueHandling = NullValueHandling.Ignore });

你可以通过 dataV2 继承 dataV1 ...然后你可以把它们放在一个列表中

public class ChartDataFactory //whatever... or directly in the controller though i don't recommend it
{
    public static IEnumerable<dataV1> GetChartData() //parameters ommited
    {
        List<dataV1> result = new List<dataV1>();
        //initialze connection/command/reader
        while (sqlReader.Read())
        {
            if (sqlReader["value"] != DBNull.Value) 
            {
                result.Add(new dataV1((string)sqlReader["time"]));
            }
            else
            {
                result.Add(new dataV2((string)sqlReader["time"],(double)sqlReader["value"]));
            }
        }
        // tear down connection
        return result;
    }
}

public class dataV1
{
    public string time { get; set; }
    public dataV1(string Ptime)
    {
        this.time = Ptime;
    }
    public dataV1() { }
}
public class dataV2 : dataV1
{
    public double value { get; set; }
    public dataV2(string Ptime, double Pvalue):base(Ptime)
    {
        this.value = Pvalue;
    }
    public dataV2() { }
}

最新更新