JSON.NET błędy deserializacji

0

Witam

Próbuję odczytać plik json, ale nie mogę sobie poradzić.

Plik JSON:

[
    {
        "Date": "2018-04-02",
        "Ts": [
            4,
            4,
            3,
            6
        ],
         "Powtorka": 3
    },
    {
        "Date": "2018-04-09",
        "Ts": [
            0
        ],
         "Powtorka": 3
    }
]

kod w C#:

public class TsListValues
       {

           public string Date { get; set; }
           public List<int> Ts { get; set; }
           public int Powtorka { get; set; }

       }

       public class TsList
       {
           public List<TsListValues> Data { get; set; }


       }

TsList ts = JsonConvert.DeserializeObject<TsList>(File.ReadAllText(@"D:\Moje Dokumenty\Dropbox\WebServ\httpd\results.json"));
          
int test = ts.Powtorka;
           JsonText.Text = test.ToString();

Wyrzuca:"
Element "Main.Window.TsList" nie zawiera definicji "Powtorka"

0

Zmień TsList na :

 public class TsList : List<TsListValues>
    {
        

    }

a potem

int test = ts.First().Powtorka;
  (...)         
0

Gdy dodam First() wyrzuca, że go Main.Window.TsList nie zawiera definicji First, a bez niego komunikat:

Newtonsoft.Json.JsonSerializationException: „Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'MySQL_conn.MainWindow+TsList' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.”

0

Ja bym usunął TsList, a potem dał:

var ts = JsonConvert.DeserializeObject<List<TsListValues>>(File.ReadAllText(@"D:\Moje Dokumenty\Dropbox\WebServ\httpd\results.json"));

a potem jak poprzednik wspomniał:

int test = ts.First().Powtorka;

oczywiście trzeba mieć using System.Linq, żeby First działało.

0
using System.Linq;

wstawione, nadal nie rozpoznaje First(). Chciałem tylko dodać, że działam na pliku WPF.

1

Skopiuj JSON
CTRL + C
Visual Studio -> Edit -> Paste Special -> Paste Json As Classes
Tadam - klasy wygenerowane.

0

froziu, trafione w punkt. dziękuję za pomoc.

1 użytkowników online, w tym zalogowanych: 0, gości: 1