This question already has answers here:
Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly
(6 answers)
Closed 8 months ago.
I have a JSON file which looks like this
{
"Response": {
"Part": {
"Name": "Part1",
"Rev": "01",
"Title": "Part1",
"current": "Released",
"Part": [
{
"Name": "Part2",
"Rev": "00",
"Title": "Part2",
"current": "Released",
"Part": {
"Name": "Part3",
"Rev": "R00",
"Title": "Part3",
"current": "Released"
}
},
{
"Name": "Part4",
"Rev": "00",
"Title": "Part4",
"current": "Released"
}
]
}
}
}
I have created my class objects as this
public class PartObj
{
public string Name { get; set; }
public string Rev { get; set; }
public string Title { get; set; }
public string current { get; set; }
public List<PartObj> Part { get; set; }
}
public class Response
{
public PartObj Part { get; set; }
}
public class Root
{
public Response Response { get; set; }
}
But I am unable to deserialize the JSON string
Root items = JsonConvert.DeserializeObject<Root>(jsonStr);
The error says
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[PartObj ]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
Any Solution for Deserializing this?
'Part' : member names cannot be the same as their enclosing type
This is why its happening:
The members of a class or struct cannot have the same name as the class or struct.
Try the following approach it should work just fine.
public class Root
{
public Response Response { get; set; }
}
public class Response
{
public Part Part { get; set; }
}
public class Part
{
public string Name { get; set; }
public string Rev { get; set; }
public string Title { get; set; }
public string current { get; set; }
public List<Part> Parts { get; set; }
}
Related
I am starting c# and I was asked to create a small Api using a given Json file as DB.
My json file looks like:
{"Items": [
{
"id": 1,
"name": "Apple",
"price": 12.50,
"image": "some url",
"description": "Some text",
"tags": [ "fruit", "red" ],
"category": "fruit"
},
]}
I created a model:
public class Product
{
public int ID { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Image { get; set; }
public string Description { get; set; }
public List<Tags> Tags { get; set; }
public string Category { get; set; }
}
public class Tags
{
public string Tag { get; set; }
}
And my controller looks like:
[ApiController]
[Route("api/[controller]")]
public class ProductController : Controller
{
[HttpGet]
public IEnumerable<Product> Get()
{
StreamReader r = new StreamReader("./items.json");
string jsonString = r.ReadToEnd();
List<Product> productsList = JsonConvert.DeserializeObject<List<Product>>(jsonString);
return productsList;
}
}
The error I get:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Kata.Product]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
As I am new to c#, I am having trouble to find out how to simply return what I have in my Json file. At some point I was able to return the list by changing the json file(not the greatest idea) but all the items were null.
Thank you
You have a bug in your json classes. You can't use a special class for the tags, try to replace it by string array or list. The same about items. You deserialized the whole Root object, items just a property of this object. So since you don't need the whole object but just list of items, you have to select only them.
var jsonDeserialized= JsonConvert.DeserializeObject<Root> (jsonString);
List<Product> productsList = jsonDeserialized.Items ;
classes
public class Product
{
public int id { get; set; }
public string name { get; set; }
public double price { get; set; }
public string image { get; set; }
public string description { get; set; }
public List<string> tags { get; set; }
public string category { get; set; }
}
public class Root
{
public List<Product> Items { get; set; }
}
and fix json
{
"Items": [{
"id": 1,
"name": "Apple",
"price": 12.50,
"image": "some url",
"description": "Some text",
"tags": ["fruit", "red"],
"category": "fruit"
}]
}
I have a json String as below, which i am using the deserialize into my class objects but I can't, here is my json.:
{
"TraceId": "24bf6a01-5d8f-4959-9173-20600a04b738",
"TransactionId": "AFC48AE50A076477C3E069296AC3F884",
"ResponseTime": "1672",
"DistanceUnits": "MI",
"CurrencyType": "GBP",
"xmlns:air": "http://www.travelport.com/schema/air_v42_0",
"air:FlightDetailsList": {
"air:FlightDetails": [
{
"Key": "hx5kk+3R2BKAuFzqAAAAAA==",
"Origin": "DXB",
"Destination": "LHE",
"DepartureTime": "2017-12-10T13:55:00.000+04:00",
"ArrivalTime": "2017-12-10T17:55:00.000+05:00",
"FlightTime": "180",
"TravelTime": "180",
"Equipment": "320",
"OriginTerminal": "1",
"DestinationTerminal": "M"
},
{
"Key": "hx5kk+3R2BKAwFzqAAAAAA==",
"Origin": "LHE",
"Destination": "DEL",
"DepartureTime": "2017-12-20T12:15:00.000+05:00",
"ArrivalTime": "2017-12-20T14:10:00.000+05:30",
"FlightTime": "85",
"TravelTime": "690",
"Equipment": "ATR",
"OriginTerminal": "M",
"DestinationTerminal": "3"
},
{
"Key": "hx5kk+3R2BKAyFzqAAAAAA==",
"Origin": "DEL",
"Destination": "DXB",
"DepartureTime": "2017-12-20T20:25:00.000+05:30",
"ArrivalTime": "2017-12-20T22:45:00.000+04:00",
"FlightTime": "230",
"TravelTime": "690",
"Equipment": "788",
"OriginTerminal": "3",
"DestinationTerminal": "1"
}
]
}
}
So I want to convert into my class LowFareSearchRsp and its FlightDetails class is also shown below:
public class LowFareSearchRsp
{
public string TraceId { get; set; }
public string TransactionId { get; set; }
public string ResponseTime { get; set; }
public string DistanceUnits { get; set; }
public string CurrencyType { get; set; }
public string air { get; set; }
public FlightDetailsList FlightDetailsList { get; set; }
}
public class FlightDetailsList
{
public List<FlightDetails> FlightDetails { get; set; }
}
public class FlightDetails
{
public string Key { get; set; }
public string Origin { get; set; }
public string Destination { get; set; }
public DateTime Departure { get; set; }
public DateTime ArrivalTime { get; set; }
public string FlightTime { get; set; }
public string TravelTime { get; set; }
public string Equipment { get; set; }
public string OriginTerminal { get; set; }
public string DestinationTerminal { get; set; }
}
and I'm using the NewtonSoft library to deserialize that json to my class object but getting the following error:
{"Cannot deserialize the current JSON object (e.g.
{\"name\":\"value\"}) into type
'System.Collections.Generic.List`1[ParseSoapEnveloperReqRes.LowFareSearchRsp]'
because the type requires a JSON array (e.g. [1,2,3]) to deserialize
correctly.\r\nTo 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.\r\nPath 'TraceId', line 2, position
12."}
Here is my code to deserialize the json string:
var LowFareSearchRsps = JsonConvert.DeserializeObject<List<LowFareSearchRsp>>(jsonString);
I'he had searched the whole internet, but can't find the solution of this. Kindly Help. Thanks.
Your JSON string represent an object not an array change deserilize code to be as below:
var LowFareSearchRsps = JsonConvert.DeserializeObject<LowFareSearchRsp>(jsonString);
Your JSON does not represent a List<LowFareSearchRsp> but a LowFareSearchRsp.
I have JSON returning in the following format:
{
"Items": [
{
"unique_id": "11111111111",
"rages": {
"rage_content": "Hello rage 2",
"date_stamp": "21/07/2017",
"id": 2
}
},
{
"unique_id": "2222222222",
"rages": {
"rage_content": "Hello rage 1",
"date_stamp": "21/07/2017",
"id": 1
}
}
],
"Count": 2,
"ScannedCount": 2
}
And I have the following 2 classes defined:
Items.cs:
namespace ragevent_A0._0._1
{
class Items
{
public String rage_id { get; set; }
public rage rage { get; set; }
}
}
rage.cs:
class rage
{
public String rage_content { get; set; }
public String date_stamp { get; set; }
public int id { get; set; }
}
I am using the following code in order to attempt to deseralize the JSON returned above:
List<Items> data = JsonConvert.DeserializeObject<List<Items>>(json);
However, I am not able to successfully deserialize the data due to the above error. I have tried a few solutions online, however I have not managed to find a solution which works with the format of my returned JSON. I have used a JSON formatter and it is formatted correctly, so that shouldn't be the issue.
Any help would be much appreciated!
For the posted JSON data below should be the model you need (credit: http://json2csharp.com/). There is mismatch between the property name rage_id. You can use JsonProperty attribute
public class Rages
{
public string rage_content { get; set; }
public string date_stamp { get; set; }
public int id { get; set; }
}
public class Item
{
[JsonProperty(Name="rage_id")]
public string unique_id { get; set; }
public Rages rages { get; set; }
}
public class RootObject
{
public List<Item> Items { get; set; }
public int Count { get; set; }
public int ScannedCount { get; set; }
}
Your deserialization should be
var data = JsonConvert.DeserializeObject<RootObject>(json);
I have an array of objects like this in json as per below format
{
Table: [
{
userstatus: [
{
STATUS: "TRUE",
PACK: "UM6MONTHPACK",
EXPIRY: "8/15/2014 1:00:03 PM",
}
]
},
{
activeauctions: [
{
ISBILLED: "0",
AUCTION_ID: "24",
AUCTION_NAME: "Swimsuit",
}
]
},
{
upcomingauctions: [
{
AUCTION_ID: "4",
AUCTION_NAME: "Jacqueline Fernandezs Handbag",
SKU: "4_20131120"
},
{
AUCTION_ID: "4",
AUCTION_NAME: "Jacqueline Fernandezs Handbag",
SKU: "4_20131120"
}
]
}
]
}
I am deserializing like this:
var outObject = JsonConvert.DeserializeObject<Table>(response);
Here are the classes I am deserializing into:
public class Userstatu
{
[Newtonsoft.Json.JsonProperty(PropertyName = "STATUS")]
public string STATUS { get; set; }
[Newtonsoft.Json.JsonProperty(PropertyName = "PACK")]
public string PACK { get; set; }
[Newtonsoft.Json.JsonProperty(PropertyName = "EXPIRY")]
public string EXPIRY { get; set; }
}
public class Activeauction
{
[Newtonsoft.Json.JsonProperty(PropertyName = "ISBILLED")]
public string ISBILLED { get; set; }
[Newtonsoft.Json.JsonProperty(PropertyName = "AUCTION_ID")]
public string AUCTION_ID { get; set; }
[Newtonsoft.Json.JsonProperty(PropertyName = "AUCTION_NAME")]
public string AUCTION_NAME { get; set; }
}
public class Upcomingauction
{
[Newtonsoft.Json.JsonProperty(PropertyName = "AUCTION_ID")]
public string AUCTION_ID { get; set; }
[Newtonsoft.Json.JsonProperty(PropertyName = "AUCTION_NAME")]
public string AUCTION_NAME { get; set; }
[Newtonsoft.Json.JsonProperty(PropertyName = "SKU")]
public string SKU { get; set; }
}
public class Table
{
[Newtonsoft.Json.JsonProperty(PropertyName = "userstatus")]
public List<Userstatu> userstatus { get; set; }
[Newtonsoft.Json.JsonProperty(PropertyName = "activeauctions")]
public List<Activeauction> activeauctions { get; set; }
[Newtonsoft.Json.JsonProperty(PropertyName = "upcomingauctions")]
public List<Upcomingauction> upcomingauctions { get; set; }
}
This fires an exception:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Data.Table]' 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 'accounts.github', line 1, position 129.
What am I doing wrong?
You are missing a class. Add this:
public class RootObject
{
public List<Table> Table { get; set; }
}
Then, deserialize like this:
var outObject = JsonConvert.DeserializeObject<RootObject>(response);
I want to Deserialize a JSON object to C# but I'm getting this exception:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'FYP___Task_1.RootObject' 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 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.
I've tried to get this error solved by different solutions I found on StackOverflow but no one worked.
The JSON I'm using is as follows:
[
{
"rating_count": 158271,
"genres": [
"Action",
"Crime",
"Thriller"
],
"rated": "PG-13",
"language": [
"English",
"French",
"Mandarin"
],
"rating": 6.7,
"country": [
"France",
"USA"
],
"release_date": 20021011,
"title": "Transporter\n \"The Transporter\"",
"year": 2002,
"filming_locations": "Avenue de Saissy, Cannes, Alpes-Maritimes, France",
"imdb_id": "tt0293662",
"directors": [
"Corey Yuen"
],
"writers": [
"Luc Besson",
"Robert Mark Kamen"
],
"actors": [
"Jason Statham",
"Qi Shu",
"Matt Schulze",
"François Berléand",
"Ric Young",
"Doug Rand",
"Didier Saint Melin",
"Tonio Descanvelle",
"Laurent Desponds",
"Matthieu Albertini",
"Vincent Nemeth",
"Jean-Yves Bilien",
"Jean-Marie Paris",
"Adrian Dearnell",
"Alfred Lot"
],
"also_known_as": [
"Transporter"
],
"poster": {
"imdb": "http://ia.media-imdb.com/images/M/MV5BMTk2NDc2MDAxN15BMl5BanBnXkFtZTYwNDc1NDY2._V1_SY317_CR3,0,214,317_.jpg",
"cover": "http://imdb-poster.b0.upaiyun.com/000/293/662.jpg!cover?_upt=cd37cf0e1385015165"
},
"runtime": [
"92 min"
],
"type": "M",
"imdb_url": "http://www.imdb.com/title/tt0293662/"
}
]
The classes I'm using:
public class Poster
{
public string imdb { get; set; }
public string cover { get; set; }
}
public class RootObject
{
public int rating_count { get; set; }
public List<string> genres { get; set; }
public string rated { get; set; }
public List<string> language { get; set; }
public double rating { get; set; }
public List<string> country { get; set; }
public int release_date { get; set; }
public string title { get; set; }
public int year { get; set; }
public string filming_locations { get; set; }
public string imdb_id { get; set; }
public List<string> directors { get; set; }
public List<string> writers { get; set; }
public List<string> actors { get; set; }
public List<string> also_known_as { get; set; }
public Poster poster { get; set; }
public List<string> runtime { get; set; }
public string type { get; set; }
public string imdb_url { get; set; }
}
Your JSON object has the structure [ {..} ] which means it is a list of objects. In your case, your list has only one object, but it is still a list. What you are trying to do is turn the list into an object, so you get an exception.
The solution is either to change your JSON to {..} (i.e. remove the square brackets) OR deserialize the JSON into an array of RootObject and then just read the first one, for example:
RootObject[] myArray = json.Deserialize<RootObject[]>("json goes here");
RootObject firstObject = myArray[0];
We can try the below option also.
var root = response1.Content.ReadAsAsync<RootObject>().Result;
GridView1.DataSource = root.items;