Json Deserealization error - c#

I try to deserialize json and write to List
Here is my ViewModel code
public async void Posts_download()
{
string url = "https://www.reddit.com/top/.json?count=50";
var json = await FetchAsync(url);
var json_new = json.ToString();
List<RootObject> rootObjectData = JsonConvert.DeserializeObject<List<RootObject>>(json);
PostsList = new List<RootObject>(rootObjectData);
}
private async Task<string> FetchAsync(string url)
{
string jsonString;
using (var httpClient = new System.Net.Http.HttpClient())
{
var stream = await httpClient.GetStreamAsync(url);
StreamReader reader = new StreamReader(stream);
jsonString = reader.ReadToEnd();
}
return jsonString;
}
And here is json response
JSON
I Have this error
How I can handle it?
UPDATE
Here is clases that I generate from json responce
Classes

The json you posted isn't an array, its a json object, however you are asking jsonconvert to deserialize to an array. Change your RootObject class and add the other classes to:
class RootObject
{
string kind {get;set}
Data data {get;set;}
List<Child> {get;set;}
}
class Data
{
string modhash {get;set;}
string before {get;set;}
string after {get;set;}
}
class Child
{
string kind {get;set;}
data .. and so on.
}
Then you would change your jsonconver line to:
RootObject rootObjectData = JsonConvert.DeserializeObject<RootObject>(json);
Please note this isn't a fully working example because it would have been cumbersome to fully define the Child class as there are many properties.
The reason this is needed is because the json posted was a json object that held an array. You can tell becuase the json started with "{", if it was an array it would have started with a "["

That JSON doesn't return an array. The RootObject should look like this:
public class RootObject
{
public string kind { get; set; }
public Data data { get; set; }
}
Then call it without the List<>:
RootObject rootObjectData = JsonConvert.DeserializeObject<RootObject>(json);
In data there is a List<Child> children. I guess you were looking for that one. Please refer to Easiest way to parse JSON response to see how to create the C# objects.

Related

How to deserialize a JSON in Blazor?

I have a JSON from an API,
{
"Cards":[
{
"ContentType":3,
"Content":"robgra"
},
{
"ContentType":4,
"Content":"Rob Graham"
},
{
"ContentType":1,
"Content":"https://www.mineralblue.net/images/robgra.jpg"
}
]
}
And i am trying to deserialize it in my .razor page. So far I have deserialized it into a string using,
using var responseStream = await response.Content.ReadAsStreamAsync();
APIreturn = await JsonSerializer.DeserializeAsync<string>(responseStream);
But i want to break it up into ConntentType and Content, i've been trying to save it as an IEnumerable object, but i keep getting an error saying the input does not contain any JSON tokens.
For example my code looks like,
Deserialized = await JsonSerializer.DeserializeAsync<IEnumerable<MyObject>>(responseStream);
But i can't figure out how to format my public class object so that i can successfully deserialize it and access individual classes.
I've tried using [JsonPropertyName("Cards"] but it didn't work. How would i format my object so i can deserialize this JSON?
Let VS do the work. Copy your JSON to a class file and use Edit | Paste Special | Paste JSON as classes and ....
public class Rootobject
{
public Card[] Cards { get; set; }
}
public class Card
{
public int ContentType { get; set; }
public string Content { get; set; }
}

Good but easy method of deserializing JSON data in c#

I've been struggling for quite a while, but now I managed to successfully pull JSON data from a web API.
My code so far (only a test snippet thus far):
var url = "http://www.trola.si/bavarski";
string text;
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = WebRequestMethods.Http.Get;
request.Accept = "application/json";
var json = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(json.GetResponseStream()))
{
text = sr.ReadToEnd();
}
As far as pulling data goes, this is ok, right?
Well here's where it gets a bit confusing. There are a lot resources online and all of them differ quite a bit. Do I need to create a class that will hold the data and { get; set; } too?
Would RESTsharp or Json.NET make my job easier? Any suggestions are appreciated.
You do not need any third party JSON libs.
Get the data to a string. You have already done this.
Create your data classes. I like igrali's idea of using Visual Studio to do it. But if the data is simple just write the class yourself:
[DataContract]
public class PersonInfo
{
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
}
Deserialize from the string to the classes:
I like to use this generic helper:
public static T Deserialize<T>(string json)
{
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
T obj = (T)serializer.ReadObject(stream);
return obj;
}
}
And then call it like this:
PersonInfo info = (PersonInfo)JsonHelper.Deserialize<PersonInfo>(s);
First of all, you will want to create classes that represent the JSON model you received. There's more than one way to do it - you can use json2csharp or even better, the Visual Studio feature called Paste JSON As Classes (find it in: Edit -> Paste Special -> Paste JSON As Classes).
Once you have the classes, you can use Json.NET to help you with the JSON response. You probably want to deserialize the string (JSON) you received to C# objects. To do it, you can just call the JsonConvert.DeserializeObject method.
var myObject = JsonConvert.DeserializeObject<MyClass>(json);
where MyClass is any kind of type you are deserializing to.
There's a WebApi client that will take care of all of the serialization for you.
http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client
Here's a sample:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:9000/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// New code:
HttpResponseMessage response = await client.GetAsync("api/products/1");
if (response.IsSuccessStatusCode)
{
Product product = await response.Content.ReadAsAsync<Product>();
Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
}
}
Json.net helps a lot with this. You can deserialize to anonymous types or POCO objects. I hope below solution helps you get started.
async Task Main()
{
using (var client = new HttpClient())
{
using (var request = new HttpRequestMessage())
{
request.RequestUri = new Uri("http://www.trola.si/bavarski");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Method = HttpMethod.Get;
var result = await client.SendAsync(request);
string jsonStr = await result.Content.ReadAsStringAsync();
Result obj = JsonConvert.DeserializeObject<Result>(jsonStr);
obj.Dump();
}
}
}
// Define other methods and classes here
public class Result
{
[JsonProperty(PropertyName = "stations")]
public Station[] Stations { get; set;}
}
public class Station
{
[JsonProperty(PropertyName = "number")]
public string Number { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "buses")]
public Bus[] Buses { get; set; }
}
public class Bus
{
[JsonProperty(PropertyName = "direction")]
public string Direction { get; set; }
[JsonProperty(PropertyName = "number")]
public string Number { get; set; }
[JsonProperty(PropertyName = "arrivals")]
public int[] Arrivals { get; set; }
}

Array JSON deserialize

I'm trying to get the data from a website RSS converting it to JSON. I got this JSON string:
http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=http%3A%2F%2Frss.tecmundo.com.br%2Ffeed
I'm using lists to get the values but I got this error "Cannot create an instance of the abstract class or interface" and I don't know how to solve it. It happens in this line.
IList<News> content = new IList<News>();
Here is my code.
public class News
{
public string author { get; set; }
public string title { get; set; }
public string content { get; set; }
public string contentSnippet { get; set; }
public string link { get; set; }
public string publishedDate { get; set; }
public string[] getFeed(string Website)
{
string path = #"http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=" + Website;
var json = new WebClient().DownloadString(path);
JObject jsonObject = JObject.Parse((string)json);
IList<JToken> jsonData = jsonObject["responseData"]["feed"]["entries"]["0"].Children().ToList();
IList<News> content = new IList<News>();
foreach(JToken data in jsonData)
{
News finalData1 = JsonConvert.DeserializeObject<News>(jsonData.ToString());
content.Add(finalData1);
}
return new string[] { "I must return something here." };
}
}
Here is the tool I'm using to visualize better the JSON string: http://jsonschema.net/#/
The error you're getting has nothing to do with JSON. It is because you're trying to create an instance of an interface. You could just fix that by giving it the concrete List<T> class:
IList<News> content = new List<News>();
However, the simpler way of converting the IList<JToken> to an IList<News> is probably to use LINQ again - you can do all of this in one step pretty easily:
IList<News> content = jsonObject["responseData"]["feed"]["entries"]["0"]
.Children()
.Select(token => JsonConvert.DeserializeObject<News>(token.ToString())
.ToList();
That compiles, but isn't actually want due to the data you've got. entries is an array, so you probably want:
JArray array = (JArray) jsonObject["responseData"]["feed"]["entries"];
var content = array
.Select(token => JsonConvert.DeserializeObject<News>(token.ToString())
.ToList();
Your problem has nothing to do with the json, but with trying to create an instance of an interface which is not possible in c#. You need to create an instance of a concrete class that implements the IList interface. List would be one example. There are others, including arrays.

Deserialize string to list class in c#

my json string data is
string r= "{"data":
[
{"ForecastID":54239761,"StatusForecast":"Done"},
{"ForecastID":54240102,"StatusForecast":"Done"},
{"ForecastID":54240400,"StatusForecast":"Done"},
{"ForecastID":54240411,"StatusForecast":"Done"},
{"ForecastID":54240417,"StatusForecast":"Done"}
]
}"
and my json class is
public class Datum
{
public string ForecastID { get; set; }
public string StatusForecast { get; set; }
}
public class RootObject
{
public List<Datum> data { get; set; }
}
i run this code
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Datum> ListAnswers = serializer.Deserialize<List<Datum>>(r);
Console.WriteLine("\n Deserialize: \n" + ListAnswers.Count );
and have 0 count of ListAnswers.Count
but should be 5 pieces.
what wrong? how to properly deserialize json string?
You need to deserialize an instance of RootObject.. since it is the root of the data. What you're trying to do right now is deserialize the whole thing as a list.. which it isn't. Its a root object with a list underneath it:
RootObject obj = serializer.Deserialize<RootObject>(r);
foreach (var item in obj.data) {
Console.WriteLine("\n Deserialize: \n" + item.ForecastID);
}
It looks like your JSON string is an object, not an array. In order to parse JSON directly into List, the JSON should be an array.
So, in your example above, if you modified your JSON string to be
[
{"ForecastID":54239761,"StatusForecast":"Done"},
{"ForecastID":54240102,"StatusForecast":"Done"},
{"ForecastID":54240400,"StatusForecast":"Done"},
{"ForecastID":54240411,"StatusForecast":"Done"},
{"ForecastID":54240417,"StatusForecast":"Done"}
]
it would parse as you are expecting it to be.
Another option would be to create a secondary C# class to reflect the structure of the JSON. Something along these lines:
public class DataContainer
{
public List<Datum> Data {get;set;}
}
This provides the 'data' property that is contained within your JSON string, so the serializer would populate the Data property with the list of Datum objects. Your calling code would then look like this:
JavaScriptSerializer serializer = new JavaScriptSerializer();
DataContainer results = serializer.Deserialize<DataContainer>(r);
Console.WriteLine("\n Deserialize: \n" + results.Data.Count );

How can I deserialize JSON containing delimited JSON?

I have a problem with deserializing a Json-string to an object.
This is a sample json i receive from a webservice:
{
"GetDataResult":
"{
\"id\":1234,
\"cityname\":\"New York\",
\"temperature\":300,
}"
}
And I have a class CityData that looks like this
[JsonObject("GetDataResult")]
public class CityData
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("cityname")]
public string CityName { get; set; }
[JsonProperty("temperature")]
public int Temperature { get; set; }
}
I try to deserialize the json with a call of the method DeserializeObject
var cityData = JsonConvert.DeserializeObject<CityData>(response);
but the root element seems to make problems...
Do you guys know how I can fix it, so that I receive a CityData-object with the data filled in?
The json response contains an object that within itself contains a json string representing the data result.
You need to deserialize twice, once for the response and one more for the data result.
var response = JsonConvert.DeserializeObject<JObject>(responseStr);
var dataResult = (string)response["GetDataResult"];
var cityData = JsonConvert.DeserializeObject<CityData>(dataResult);

Categories

Resources