Cannot deserialize the current JSON array in C# - c#

I'm attempting to switch from VB.NET to C#; however I'm having some issues with JSON. I'm attempting to deserialize a JSON array. However, I get this error:
Cannot deserialize the current JSON array
Here's the class I'm deserializing into:
public class ReturnObject
{
public int id { get; set; }
public string name { get; set; }
public string url { get; set; }
public bool thumbnailFinal { get; set; }
public string thumbnailUrl { get; set; }
public object bcOverlayUrl { get; set; }
public object personalServerOverlayUrl { get; set; }
}
Deserialize code:
Debug.WriteLine(JsonConvert.DeserializeObject<ReturnObject>(richTextBox1.Text));
Here's the web URL to the JSON I'm attempting to retrieve.
http://www.roblox.com/place-thumbnails?params=[{placeId:1818}]

You're trying to deserialize a JSON array into just a single object, which can't be done.
Change your deserialization code to this:
var deserialized = JsonConvert.DeserializeObject<ReturnObject[]>(richTextBox1.Text)
To see the results:
foreach(var obj in deserialized)
{
Debug.WriteLine(obj.id);
}

Related

Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {“name”:“value”}) to deserialize correctly

hi im trying to download data from api and then try some linq on it but i cant even display it normaly.
dynamic type works propelly but i cant use linq with it
im using this api
http://api.nbp.pl/api/exchangerates/tables/a/?format=json
my class in c#
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string table { get; set; }
public string no { get; set; }
public string effectiveDate { get; set; }
public Rate[] rates { get; set; }
}
public class Rate
{
public string currency { get; set; }
public string code { get; set; }
public float mid { get; set; }
}
the code to deserialize :
using (WebClient client = new WebClient())
{
String text = Encoding.UTF8.GetString(client.DownloadData("http://api.nbp.pl/api/exchangerates/tables/a/?format=json"));
var Data = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(text);
Debug.WriteLine(Data);
}
when i put it in array or list (like this)
var Data = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject[]>(text);
i can only see the class path
To correctly represent json returned by provided link you can use array of Class1, not Rootobject:
var Data = Newtonsoft.Json.JsonConvert.DeserializeObject<Class1[]>(text);

Newtonsoft.Json not serializing object as expected - error 400

I'm trying to send a post request with a json string of an object I have created. However after serializing my c# object and posting I get a 400 error (problems parsing JSON)
I'm using the Newtonsoft.Json dll to serialize my object. Here is the object I am serializing:
public class CreateRepository
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("homepage")]
public object Homepage { get; set; }
[JsonProperty("gitignore_template")]
public string GitIgnoreTemplate { get; set; }
[JsonProperty("license_template")]
public string LicenceTemplate { get; set; }
[JsonProperty("private")]
public bool Private { get; set; }
[JsonProperty("has_projects")]
public bool HasProjects { get; set; }
[JsonProperty("has_issues")]
public bool HasIssues { get; set; }
[JsonProperty("has_template")]
public bool HasTemplate { get; set; }
[JsonProperty("has_wiki")]
public bool HasWiki { get; set; }
}
I am then serializing an instance of the object like so:
var content = JsonConvert.SerializeObject(repository);
This then generates the json string below:
{
\"name\": \"Test\",
\"description\":null,
\"homepage\":null,
\"gitignore_template\":null,
\"license_template\":null,
\"private\":false,
\"has_projects\":false,
\"has_issues\":false,
\"has_template\":false,
\"has_wiki\":false}
}
I get the following back after attempting to post the request:
{
"message": "Problems parsing JSON",
"documentation_url": "https://developer.github.com/v3/repos/#create"
}
Does anyone know why my object has been serialized in this way?
Update:
I can deserialize the object using JSON.Net without any errors.
The url I'm posting to is as follows:
https://api.github.com/user/repos
this is how I'm sending the request:
var response = await _httpClient.PostAsJsonAsync("user/repos", content);
The problem is that "has_template" is unknown at Github side and probably should be "is_template". See the link you got back in the response of your request for the correct parameter names. So you are not using the correct property names/name attributes in your Class. Serialization is not the issue.

Converting JSON to Object fails - Cannot deserialize the current JSON object into System.Collections.Generic.List

I'm using the API of www.textlocal.in, which returns a JSON formatted object.
JSON
{
"warnings":[
{
"message":"Number is in DND",
"numbers":"917000000000"
}
],
"balance":900,
"batch_id":311110011,
"cost":1,
"num_messages":1,
"message":{
"num_parts":1,
"sender":"TXTLCL",
"content":"Test1"
},
"receipt_url":"",
"custom":"",
"inDND":[
"917000000000"
],
"messages":[
{
"id":"1350123781",
"recipient":918819437284
}
],
"status":"success"
}
My code with which I'm trying to parse the JSON:
private void button1_Click(object sender, EventArgs e)
{
var a = JsonConvert.DeserializeObject<List<jsonToObj[]>>(richTextBox1.Text);
}
public class jsonToObj
{
public warnings[] warnings { get; set; }
public int balance { get; set; }
public int batch_id { get; set; }
public int cost { get; set; }
public int num_messages { get; set; }
public message message { get; set; }
public string receipt_url { get; set; }
public string custom { get; set; }
public messages[] messages { get; set; }
public string status { get; set; }
}
public class warnings
{
public string message { get; set; }
public string numbers { get; set; }
}
public class messages
{
public string id { get; set; }
public int recipient { get; set; }
}
public class message
{
public int num_part { get; set; }
public string sender { get; set; }
public string content { get; set; }
}
I'm getting an exception with the following message:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the
current JSON object (e.g. {"name":"value"}) into type
'System.Collections.Generic.List`1[WindowsFormsApp1.Form2+jsonToObj[]]'
because the type requires a JSON array (e.g. [1,2,3]) to deserialize
correctly. To fix this error either change the JSON to a JSON array
(e.g. [1,2,3]) or change the deserialized type so that it is a normal
.NET type (e.g. not a primitive type like integer, not a collection
type like an array or List) that can be deserialized from a JSON
object. JsonObjectAttribute can also be added to the type to force it
to deserialize from a JSON object. Path 'warnings', line 1, position
12.'
First of all you have to figure out what your API returns.
Right now you're trying to parse a List of jsonToObj Arrays (List<jsonToObj[]>). You have to decide whether to use a jsonToObj[] or List<jsonToObj> or a simple jsonToObj which your API provides now:
var a = JsonConvert.DeserializeObject<jsonToObj>(richTextBox1.Text);
But this then throws:
JSON integer 918819437284 is too large or small for an Int32. Path 'messages[0].recipient', line 25, position 33."
So make sure you use a Long for that.
public class messages
{
public string id { get; set; }
public long recipient { get; set; }
}
Furthermore you can add inDND to your jsonToObj class if you need the info:
public class jsonToObj
{
...
public string[] inDND { get; set; }
...
}
Based on string you class structure should be like this :
public class Warning
{
public string message { get; set; }
public string numbers { get; set; }
}
public class Message
{
public int num_parts { get; set; }
public string sender { get; set; }
public string content { get; set; }
}
public class Message2
{
public string id { get; set; }
public long recipient { get; set; }
}
public class RootObject
{
public List<Warning> warnings { get; set; }
public int balance { get; set; }
public int batch_id { get; set; }
public int cost { get; set; }
public int num_messages { get; set; }
public Message message { get; set; }
public string receipt_url { get; set; }
public string custom { get; set; }
public List<string> inDND { get; set; }
public List<Message2> messages { get; set; }
public string status { get; set; }
}
It looks like your class structure is not proper, Make use of visual studio and generate C# class from json string and then using that generated class try to deserialize class.
Read : Visual Studio Generate Class From JSON or XML
I simulated your problem and made the following changes that worked:
Change the method that deserializes to this:
var a = JsonConvert.DeserializeObject<jsonToObj>(richTextBox1.Text);
The result of the JSON you receive is not a List, so it will not work to deserialize to List<>.
The recipient property of the messages class receives values larger than an integer, so it must be transformed into a long like this:
public long recipient { get; set; }
These changes solve your problem.
Looks like this is a very old post, still thought of answering.
First of all, your Json data is singular which means, either
var a = JsonConvert.DeserializeObject<List<jsonToObj[]>>(richTextBox1.Text);
or
var a = JsonConvert.DeserializeObject<List<jsonToObj>>(richTextBox1.Text);
may not work for you.
You can either try:
var a = JsonConvert.DeserializeObject<jsonToObj>(richTextBox1.Text);
or
enclose the data with [ and ], which would do the trick.
make sure your parsing single object vs list of objects.

Error when deserializing JSON from League of Legends API

I am trying to use RiotGames Api. I have JSON data and I need to deserialize this JSON to c# classes but I get an error:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[WFALeagueOfLegendsAPI.Heroes]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'datas.Aatrox', line 1, position 85.'
My Classes:
public class JsonRoot
{
public string type { get; set; }
public string format { get; set; }
public string version { get; set; }
public List<Heroes> datas { get; set; }
}
public class Heroes
{
public HeroesData Name { get; set; }
}
public class HeroesData
{
public string version { get; set; }
public string id { get; set; }
public string key { get; set; }
public string name { get; set; }
public string title { get; set; }
public HeroImage image { get; set; }
}
public class HeroImage
{
public string full { get; set; }
public string sprite { get; set; }
public string group { get; set; }
public override string ToString()
{
return full;
}
}
C# Code:
var json = new WebClient().DownloadString("http://ddragon.leagueoflegends.com/cdn/6.24.1/data/en_US/champion.json");
json = json.Replace("data", "datas");
JsonRoot jr = JsonConvert.DeserializeObject<JsonRoot>(json); // this line has the error
You are getting this error because you are using a List<Heroes> for the data, but that property is not an array in the JSON. You need to use a Dictionary<string, HeroesData> instead. The heroes' names will be the keys of the dictionary. Also, if you want to use a different name for a particular property in your class than what is in the JSON, you can use a [JsonProperty] attribute, as shown below. It's not really a good idea to use string.Replace to try to change the JSON to suit your classes, because you could end up replacing things you did not intend.
public class JsonRoot
{
public string type { get; set; }
public string format { get; set; }
public string version { get; set; }
[JsonProperty("data")]
public Dictionary<string, HeroesData> heroes { get; set; }
}
Fiddle: https://dotnetfiddle.net/kuKSrk

Deserialising json with JSON.NET - Cannot deserialise because the type requires a JSON array

Trying to read json via an API but getting the following error: I've tried a few things but always seem to get this error..
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Shared.Review]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'status', line 1, position 10.
Model:
public class Reviewer
{
public string first_name { get; set; }
public string last_name { get; set; }
public string verified_buyer { get; set; }
public string profile_picture { get; set; }
}
public class Review
{
public string product_review_id { get; set; }
public string name { get; set; }
public string review { get; set; }
public string rating { get; set; }
public string date_created { get; set; }
public string timeago { get; set; }
public string date_formatted { get; set; }
public string product { get; set; }
public List<object> ratings { get; set; }
public Reviewer reviewer { get; set; }
}
public class RootObject
{
public string status { get; set; }
public List<Review> reviews { get; set; }
public int count { get; set; }
public string rating { get; set; }
public string per_page { get; set; }
public string current_page { get; set; }
public int total_pages { get; set; }
}
c# Code:
var reviews = JsonConvert.DeserializeObject<List<Review>>(json);
StringBuilder reviewsString = new StringBuilder();
foreach (var review in reviews)
{
reviewsString.AppendFormat("<div class=\"review\">");
reviewsString.AppendFormat("<p class=\"review-title\">Snugg Case</p>");
reviewsString.AppendFormat("<div class=\"rating\">");
reviewsString.AppendFormat("<span class=\"star\"></span>");
reviewsString.AppendFormat("<span class=\"star\"></span>");
reviewsString.AppendFormat("<span class=\"star\"></span>");
reviewsString.AppendFormat("<span class=\"star\"></span>");
reviewsString.AppendFormat("<span class=\"halfStar\"></span>");
reviewsString.AppendFormat("</div>");
reviewsString.AppendFormat("<p class=\"review-details\">{0}</p>",
review.review);
reviewsString.AppendFormat("<p class=\"review-name\">{0}</p>",
review.name);
reviewsString.AppendFormat("<p class=\"review-date\">{0}</p>",
review.date_formatted);
reviewsString.AppendFormat("</div> ");
topSectionReviews.Text += reviewsString;
}
Example Json:
http://pastebin.com/HNhNDMhr
Any questions just ask
Thanks in advance,
Michael
You're trying to deserialize into a collection:
var reviews = JsonConvert.DeserializeObject<List<Review>>(json);
However your Json isn't a collection at the top level since that would mean the json string would start and end with []. Instead it is surrounded by {} which indicates a single object.
It looks like you want to deserialize as a single RootObject instead:
var reviews = JsonConvert.DeserializeObject<RootObject>(json);
since this has a field List<Review> reviews and string status.
Not that you are not following naming conventions. Use proper naming and the [JsonProperty("something")] attribute to correctly parse the json.

Categories

Resources