Parse Json Array objects using Newtonsoft.Json - c#

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);

Related

JSON deserialize same object within object [duplicate]

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; }
}

Deserialize JSON not working with newtonsoft.json

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.

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

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);

Convert JSON array to a c# object collection

I've a JSON like below,
[
{
"document":
{
"createdDate":1476996267864,
"processedDate":1476996267864,
"taxYear":"2015",
"type":"user_document"
}
},
{
"document":
{
"createdDate":1476998303463,
"processedDate":0,
"taxYear":"2015",
"type":"user_document"
}
}
]
I need to convert it into a c# object. My object type is as below-
public class UserDocument
{
[JsonProperty(PropertyName = "type")]
public string type { get; set; }
[JsonProperty(PropertyName = "taxYear")]
public string taxYear { get; set; }
[JsonProperty(PropertyName = "createdDate")]
public string createdDate { get; set; }
[JsonProperty(PropertyName = "processedDate")]
public string processedDate { get; set; }
}
I'm using below code to deserialize the json but all UserDocument properties are null
var test = JsonConvert.DeserializeObject<List<UserDocument>>(jsonString);
Why am I getting all UserDocument properties are null, what's wrong here? I'm not getting any error.
Also can you suggest a good example in getting CouchBase queryresult into a .net object.
Seems your json is not in correct format. If I say your json is like
[
"document":
{
"createdDate":1476996267864,
"processedDate":1476996267864,
"taxYear":"2015",
"type":"user_document"
},
"document":
{
"createdDate":1476998303463,
"processedDate":0,
"taxYear":"2015",
"type":"user_document"
}
]
Then create a model like
public class Document
{
public UserDocument document {get;set;}
}
and change your UserDocument model's createdDate and processedDate properties as double because its like that in your json
public class UserDocument
{
[JsonProperty(PropertyName = "type")]
public string type { get; set; }
[JsonProperty(PropertyName = "taxYear")]
public string taxYear { get; set; }
[JsonProperty(PropertyName = "createdDate")]
public double createdDate { get; set; }
[JsonProperty(PropertyName = "processedDate")]
public double processedDate { get; set; }
}
and then deserialize
var test = JsonConvert.DeserializeObject<List<Document>>(jsonString);
Something like this (using Newtonsoft.Json.Linq):
var documents = JArray.Parse(json).Select(t => t["document"].ToObject<UserDocument>());

Deserialise JSON with Newtonsoft Json.NET in C#

I want to parse a piece of JSON with Newtonsoft Json.NET
JSON:
[{
"type": "switchStatus",
"Data" :[
{
"ID" : "1",
"value" : "2.5"
},
{
"ID" : "2",
"value" : "4.2"
}
],
"Datetime": "2014-12-01",
"customerID": "50"
}]
Classes:
public class Account
{
[JsonProperty("type")]
public string Type { get; set; }
public List<Data> Data { get; set; }
[JsonProperty("Datetime")]
public string DateTime { get; set; }
[JsonProperty("customerID")]
public string CustomerId { get; set; }
}//Account
public class Data
{
[JsonProperty("ID")]
public string Id { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
Parsing:
Account account = JsonConvert.DeserializeObject<Account>(message);
Error :
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'JSonParser.Account' 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.
Your problem is that your JSON doesn't match your declared class. Specifically, your Data property isn't a List<string>, its a complex object.
Your class should look like this:
public class Data
{
[JsonProperty("ID")]
public int Id { get; set; }
[JsonProperty("value")]
public double Value { get; set; }
}
public class Account
{
[JsonProperty("type")]
public string Type { get; set; }
public List<Data> Data { get; set; }
[JsonProperty("Datetime")]
public string DateTime { get; set; }
[JsonProperty("customerID")]
public int CustomerId { get; set; }
}
Edit:
As you've edited your JSON, it's clear now that you need a List<Account>, and not a single one. When you deserialize, you'll need:
List<Account> accounts = JsonConvert.DeserializeObject<List<Account>>(message);
You cannot Deserialize the data Data attribute like that. Since the list isnt a string to start with.
Try:
public class Data
{
public int ID { get; set; }
public float value { get; set; }
}//Data
public class Account
{
public string type { get; set; }
public List<Data> Data { get; set; }
public string Datetime { get; set; }
public string customerID { get; set; }
}//Account

Categories

Resources