Как правильно десериализовать JSON? - C#
Формулировка задачи:
Подскажите, что я делаю не так?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string json = "{\"success\":true,\"price_prefix\":\"\",\"price_suffix\":\" pуб.\",\"prices\":[[\"Jul 15 2015 16: +0\",1.745,\"6\"],[\"Jul 15 2015 17: +0\",1.78,\"5\"],[\"Jul 15 2015 18: +0\",1.65,\"7\"]]}";
Newtonsoft.Json.Linq.JObject obj = Newtonsoft.Json.Linq.JObject.Parse(json);
Price[] objArr = JsonConvert.DeserializeObject<Price[]>(obj["prices"].ToString());
foreach (Price Obj in objArr)
{
Console.WriteLine("Date: {0}", Obj.date);
Console.WriteLine("Price: {0}", Obj.price);
Console.WriteLine("Count: {0}", Obj.count);
Console.WriteLine(new string('-', 10));
}
Console.ReadKey(true);
}
}
[JsonObject(MemberSerialization.OptIn)]
struct Price
{
public string date { get; set; }
public string price { get; set; }
public string count { get; set; }
}
}Решение задачи: «Как правильно десериализовать JSON?»
textual
Листинг программы
var prices = JObject.Parse(json)["prices"].Children()
.Select(j => new PriceItem
{
Date = ConvertPriceDate(j[0].ToString()),
Price = (float)j[1],
Count = (int)j[2]
});
...
static DateTime ConvertPriceDate(string s)
{
return DateTime.ParseExact(s, "MMM dd yyyy HH':' z", CultureInfo.InvariantCulture);
}