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

时间:2015-04-16 09:37:37

标签: c# json

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

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

我创建了两个类:

  • dataV1(时间)
  • 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) 

如果值为null,我如何组合这两个类并使用dataV1?当我们有一个非空值时,如何使用dataV2

并检索Json结果

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

2 个答案:

答案 0 :(得分:5)

您可以将dataV2课程(我建议将其名称更改为更有意义的内容)设置double?可空字段而不是double。这样,对于JSON中存在“value”字段的情况,您不必复制对象:

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 });

答案 1 :(得分:1)

您可以通过dataV2继承dataV1 ...然后您可以将它们放入List&lt; dataV1&gt; :

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() { }
}