使用json.net返回数组而不是对象数组

时间:2013-12-13 00:37:31

标签: c# arrays json json.net

我需要返回一个数组数组,而不是一个flot图表的对象数组。

我可以得到以下内容:

data = [{"2012-10": 4140},{"2012-11": 10815},{"2012-12": 10444}];

但需要(UPDATE固定以下行):

data = [["2012-10", 4140],["2012-11", 10815],["2012-12", 10444]];

这是从另一个源解析入站json的c#:

public async Task<ActionResult> Chart(string custid)
   {
        //Get the financial results from DRT
        var response = await DominoJSON.getJSON(custid, "drtHistory", "DRT");

        JArray UOVol = new JArray();

        var array = JArray.Parse(response);
        foreach (var token in array)
        {
            JObject o = JObject.Parse(token.ToString());

            int uovol = Convert.ToInt32(o["UOVol"]);
            string uodate = o.SelectToken("DATE").ToString();
            JObject UOItem = new JObject(new JProperty(uodate, uovol));
            UOVol.Add(UOItem);

        }

       string resultUO = UOVol.ToString();

       ViewBag.UOData = resultUO;

        return View();
    }

正在解析入站json:

   [
  {
      "DATE":"2012-10",
      "UOVol":4140,
      "FIRev":180,
      "AFRev":692.75,
      "ABRev":2900,
      "OWRev":3791.25,
  },
  {

      "DATE":"2012-11",
      "UOVol":10815,
      "FIRev":60,
      "AFRev":170,
      "ABRev":0,
      "OWRev":3037.5,
  },
  {

      "DATE":"2012-12",
      "UOVol":10444,
      "FIRev":40,
      "AFRev":514.25,
      "ABRev":1450,
      "OWRev":7500,
  }
]

我无法弄清楚如何将JObject转换为数组。我已尝试过其他方法,包括使用字典和列表。任何帮助或替代解决方案都会有所帮助。使用VS2013,mvc 5和EF 6。

1 个答案:

答案 0 :(得分:3)

试试这个:

class Program
{
    static void Main(string[] args)
    {
        string jsonIn = @"
        [
            {
                ""DATE"": ""2012-10"",
                ""UOVol"": 4140,
                ""FIRev"": 180,
                ""AFRev"": 692.75,
                ""ABRev"": 2900,
                ""OWRev"": 3791.25
            },
            {
                ""DATE"": ""2012-11"",
                ""UOVol"": 10815,
                ""FIRev"": 60,
                ""AFRev"": 170,
                ""ABRev"": 0,
                ""OWRev"": 3037.5
            },
            {
                ""DATE"": ""2012-12"",
                ""UOVol"": 10444,
                ""FIRev"": 40,
                ""AFRev"": 514.25,
                ""ABRev"": 1450,
                ""OWRev"": 7500
            }
        ]";

        JArray arrayIn = JArray.Parse(jsonIn);
        JArray arrayOut = new JArray();
        foreach (JObject jo in arrayIn.Children<JObject>())
        {
            JArray ja = new JArray();
            ja.Add(jo["DATE"]);
            ja.Add(jo["UOVol"]);
            arrayOut.Add(ja);
        }

        string jsonOut = arrayOut.ToString(Formatting.None);
        Console.WriteLine(jsonOut);
    }
}

输出:

[["2012-10",4140],["2012-11",10815],["2012-12",10444]]