Answer the question
In order to leave comments, you need to log in
How to properly deserialize json into a C# object?
Can't deserialize json properly. I have not seen such a structure before, I don’t know how to describe the class correctly.
Here is an example of a server response
{
"time": 1556008469,
"states": [
[
"4248f4",
"AFL2040 ",
"United Kingdom",
1556008469,
1556008469,
24.8216,
52.5425,
10363.2,
false,
236.66,
233.75,
0,
null,
10347.96,
"5123",
false,
0
],
[
"471f82",
"",
"Hungary",
1556008469,
1556008469,
26.7204,
52.2582,
10972.8,
false,
238.44,
237.06,
0,
null,
11003.28,
"6230",
false,
0
]
]
}
public class Answer
{
public int time { get; set; }
public List<List<object>> states { get; set; }
}
using System;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using QuickDeser;
namespace ConsoleApplication2
{
internal class Program
{
public static void Main(string[] args)
{
WebRequest request = WebRequest.Create("https://opensky-network.org/api/states/all?lamin=51.421812&lomin=23.139124&lamax=55.961184&lomax=33.472494");
WebResponse response = request.GetResponse();
Answer answer;
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
string line = "";
try
{
answer = JsonConvert.DeserializeObject<Answer>(line);
Console.WriteLine(answer.ToString());
}
catch (NullReferenceException e)
{
Console.WriteLine("Ничего нету");
throw;
}
}
}
response.Close();
Console.WriteLine("Запрос выполнен");
Console.Read();
}
}
}
Answer the question
In order to leave comments, you need to log in
Added comments to a piece of your code.
string line = "";
try
{
// line всё ещё пустая
answer = JsonConvert.DeserializeObject<Answer>(line); // десериализация из пустой строки
Console.WriteLine(answer.ToString());
}
Fixed code
string fullJson = "";
string line = "";
while ((line = reader.ReadLine()) != null)
{
fullJson += line;
}
// Console.WriteLine(fullJson);
try
{
answer = JsonConvert.DeserializeObject<Answer>(fullJson);
// думал распарсить то что получилось еще раз, но answer же теперь не строка а объект)
// это класс для парсинга дальше
// public class SecondLevelDeser
// {
// public List<object> state { get; set; }
// }
// так пробывал парсить
// secondLevelDeser = JsonConvert.DeserializeObject<SecondLevelDeser>(answer);
Console.WriteLine(answer);
}
catch (NullReferenceException e)
{
Console.WriteLine("Ничего нету");
throw;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question