.Net Fiddle 1
I have a JOSN received from external API as follows
[{
"assignedto": "MAIN STAFF",
"createduser": "API-71",
"departmentid": "1",
"observations": [{
"abnormalflag": "abnormal",
"analytename": "HGB A1C",
"value": "5"
}],
"pages": [],
"priority": "2",
"status": "REVIEW"
}]
I did a Paste Special in Visual Studio and got following classes
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string assignedto { get; set; }
public string createduser { get; set; }
public string departmentid { get; set; }
public Observation[] observations { get; set; }
public object[] pages { get; set; }
public string priority { get; set; }
public string status { get; set; }
}
public class Observation
{
public string abnormalflag { get; set; }
public string analytename { get; set; }
public string value { get; set; }
}
When I do a deserialization, I am getting following error
Run-time exception (line 24): Cannot deserialize the current JSON array (e.g. [1,2,3]) into type '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.
C# Code
public static void Main(string[] args)
{
var json = #"[{
""assignedto"": ""MAIN ST (HUB) STAFF"",
""createduser"": ""API-7127"",
""departmentid"": ""1"",
""observations"": [{
""abnormalflag"": ""abnormal"",
""analytename"": ""HGB A1C"",
""value"": ""5""
}],
""pages"": [],
""priority"": ""2"",
""status"": ""REVIEW""
}]";
Rootobject resultObj = JToken.Parse(json).ToObject<Rootobject>();
}
I referred similar questions like Create a strongly typed c# object from json object with ID as the name - but that is a different issue.
Any idea how to fix this? Also what is the better way to generate C# classes from JSON?
Note: I also tried with class I got from http://json2csharp.com/. That also faield - Fidlle 2
I would use Newtonsoft / Json convert and change this:
Rootobject resultObj = JToken.Parse(json).ToObject<Rootobject>();
to:
using Newtonsoft.Json;
-- snip --
var resultObj = JsonConvert.DeserializeObject<List<Class1>>(json);
Console.WriteLine(resultObj.Count); // 1
Class1 result = resultObj[0];
Console.WriteLine(result.assignedto); // "MAIN ST (HUB) STAFF"
This will give you a collection of RootObject
As #JeffMeracdo states above - you are providing a collection of object and trying to parse as though it is a single object
As #JeffMeracdo states above, try this:
List<Example> resultObj = JsonConvert.DeserializeObject<List<Example>>(json);
Following using statement and package along with Newtonsoft.Json Nuget package:
using Newtonsoft.Json;
Classes:
public class Observation
{
public string abnormalflag { get; set; }
public string analytename { get; set; }
public string value { get; set; }
}
public class Example
{
public string assignedto { get; set; }
public string createduser { get; set; }
public string departmentid { get; set; }
public List<Observation> observations { get; set; }
public List<object> pages { get; set; }
public string priority { get; set; }
public string status { get; set; }
}
Related
I am trying to deserialize a JSON string and for some reason it will not work.
string json_string = "{'CartID':{'ID':253419,'AuthenticatedKey':223239},'CustomerID':null,'PurchaseItems':null,'TenderInformation':null,'ModifyCartItems':null,'AdditionalCartInformation':{'ServiceInformation':{'ServiceInformationItem':[{'ServiceID':243401}]}}}";
modifyCartReq = JsonConvert.DeserializeObject<ModifyCartReq>(json_string);
I have also tried the following
string json_string = "{'CartID':{'ID':253419,'AuthenticatedKey':223239},'CustomerID':null,'PurchaseItems':null,'TenderInformation':null,'ModifyCartItems':null,'AdditionalCartInformation':{'ServiceInformation':{'ServiceInformationItem':[{'ServiceID':243401}]}}}";
modifyCartReq = JsonSerializer.Deserialize<ModifyCartReq>(json_string);
I get the same error below
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'ExampleType' 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 'AdditionalCartInformation.ServiceInformation.ServiceInformationItem', line 1, position 213.
From my attempts at solving this It feels like some syntax issue is ultimately the cause of this.
you have to fix json_string
{
"CartID": {
"ID": 253419,
"AuthenticatedKey": 223239
},
"CustomerID": null,
"PurchaseItems": null,
"TenderInformation": null,
"ModifyCartItems": null,
"AdditionalCartInformation": {
"ServiceInformation": {
"ServiceInformationItem": [{
"ServiceID": 243401
}]
}
}
}
try this
modifyCartReq = JsonSerializer.Deserialize<Root>(json_string);
and use this classes
public class CartID
{
public int ID { get; set; }
public int AuthenticatedKey { get; set; }
}
public class ServiceInformationItem
{
public int ServiceID { get; set; }
}
public class ServiceInformation
{
public List<ServiceInformationItem> ServiceInformationItem { get; set; }
}
public class AdditionalCartInformation
{
public ServiceInformation ServiceInformation { get; set; }
}
public class Root
{
public CartID CartID { get; set; }
public object CustomerID { get; set; }
public object PurchaseItems { get; set; }
public object TenderInformation { get; set; }
public object ModifyCartItems { get; set; }
public AdditionalCartInformation AdditionalCartInformation { get; set; }
}
just replace objects with your real types.
I am trying to deserialize a JSON response, but I am doing something wrong when creating the data models.
I deserialize normally with EventsData resultJSON = JsonConvert.DeserializeObject<EventsData>(jsonText);
JSON contains list of events such as:
{
"#event_no":"6924",
"#name":"REDACTED",
"Show":{
"#show_no":"1",
"#show_datetime":"2007-04-05 15:00:00"
}
},
{
"#event_no":"6925",
"#name":"REDACTED",
"Show":{
"#show_no":"1",
"#show_datetime":"2007-04-15 15:00:00"
}
}
My data model:
public class Show
{
[JsonProperty("#show_no")]
public string show_no { get; set; }
[JsonProperty("#show_datetime")]
public string show_datetime { get; set; }
}
public class Event
{
[JsonProperty("#event_no")]
public string event_no { get; set; }
[JsonProperty("#name")]
public string name { get; set; }
public Show Show { get; set; }
}
public class Events
{
public List<Event> Event { get; set; }
}
public class EventsData
{
public Events Events { get; set; }
}
However, when I am trying to deserialize I get the following error:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the
current JSON array (e.g. [1,2,3]) into type 'VM_Models.Show' 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.
What exactly am I doing wrong? If I make the Show property dynamic instead of class Show then it works
UPDATE: I did find in the data sometimes there are more than one shows:
{
"#event_no":"54535",
"#name":"REDACTED",
"Show": [
{
"#show_no": "1",
"#show_datetime": "2009-05-06 19:00:00"
},
{
"#show_no": "2",
"#show_datetime": "2009-05-07 19:00:00"
},
{
"#show_no": "3",
"#show_datetime": "2009-05-08 19:00:00"
},
{
"#show_no": "4",
"#show_datetime": "2009-05-09 19:00:00"
},
{
"#show_no": "5",
"#show_datetime": "2009-05-10 19:00:00"
}
]
}
The problem was I was converting from XML to JSON to Object. I've decided to go from XML to object directly:
[XmlRoot(ElementName = "Show", Namespace = "http://REDACTED/schema")]
public class Show
{
[XmlAttribute(AttributeName = "show_no")]
public string Show_no { get; set; }
[XmlAttribute(AttributeName = "show_datetime")]
public string Show_datetime { get; set; }
}
[XmlRoot(ElementName = "Event", Namespace = "http://REDACTED/schema")]
public class Event
{
[XmlElement(ElementName = "Show", Namespace = "http:/REDACTED/schema")]
public List<Show> Show { get; set; }
[XmlAttribute(AttributeName = "event_no")]
public string Event_no { get; set; }
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
}
[XmlRoot(ElementName = "Events", Namespace = "http://REDACTED/schema")]
public class Events
{
[XmlElement(ElementName = "Event", Namespace = "http://REDACTED/schema")]
public List<Event> Event { get; set; }
[XmlAttribute(AttributeName = "xmlns")]
public string Xmlns { get; set; }
}
Then in the code:
XmlSerializer serializer = new XmlSerializer(typeof(Events));
TextReader reader = new StringReader(response.Content);
Events result = (Events)serializer.Deserialize(reader);
Now I am able to see all data properties normally.
I am trying to deserialise some JSON that I get back from an API so that I can loop through an array of county names and add the information to a datatable in C#. However I am receiving following error at the first hurdle when I try and deserialise it:
error: System.MissingMethodException: No parameterless constructor defined for type of 'DPDJSONLibrary.DPD_JSON+LOCR_Data[]'.
The provider of the API provides an example of the JSON response as follows:
{
"error": null,
"data":[{
"country": [{
"countryCode":"GB",
"countryName":"United Kingdom",
"internalCode":"UK",
"isEUCountry":false,
"isLiabilityAllowed":false,
"isoCode":"826",
"isPostcodeRequired":false,
"liabilityMax":15000
}]
}]
}
A sample of the JSON data I am getting back from the API is:
{
"data": {
"country":[
{
"countryCode":"PM",
"countryName":"St Pierre & Miquilon",
"isoCode":"666",
"isEUCountry":false,
"isLiabilityAllowed":true,
"liabilityMax":15000,
"isPostcodeRequired":true
},
{
"countryCode":"SR",
"countryName":"Suriname",
"isoCode":"740",
"isEUCountry":false,
"isLiabilityAllowed":true,
"liabilityMax":15000,
"isPostcodeRequired":true
},
{
"countryCode":"SZ",
"countryName":"Swaziland",
"isoCode":"748",
"isEUCountry":false,
"isLiabilityAllowed":true,
"liabilityMax":15000,
"isPostcodeRequired":true
}
]
}
}
I have tried to make some classes to put the JSON in as follows:
/// <summary>
/// List Of Countries Response object.
/// </summary>
public class LOCR
{
public LOCR_Error error { get; set; }
public LOCR_Data[] data { get; set; }
}
public class LOCR_Error
{
public string errorAction { get; set; }
public string errorCode { get; set; }
public string errorMessage { get; set; }
public string errorObj { get; set; }
public string errorType { get; set; }
}
public class LOCR_Data
{
public LOCR_Data_Country[] country { get; set; }
}
public class LOCR_Data_Country
{
public string countryCode { get; set; }
public string countryName { get; set; }
public string internalCode { get; set; }
public bool isEUCountry { get; set; }
public bool isLiabilityAllowed { get; set; }
public string isoCode { get; set; }
public bool isPostcodeRequired { get; set; }
public int liabilityMax { get; set; }
}
When I get the JSON back as a string, I am trying to use the Newtonsoft (plugin?) to put it into my classes using:
JavaScriptSerializer ser = new JavaScriptSerializer();
DPD_JSON.LOCR DPDCountries = new DPD_JSON.LOCR();
DPDCountries = ser.Deserialize<DPD_JSON.LOCR>(data);
It is the last line above that is generating the error. I suspect I've written my classes wrong that I am trying to deserialise the JSON in to - can anyone see where I've gone wrong?
Deserialize will return a list and not an array, So your LOCR_Data_Country should be of type List and not array:
public class LOCR_Data
{
public List<LOCR_Data_Country> country { get; set; }
}
There's a HUGE difference between the two example JSON strings you've shown. Mainly the first one is an array : "data":[ ... ] and the second one is an object "data:{ ... }. These two are not interchangeable so you have to stick to either one of those. If the thing you're getting back from the API is an object instead you should rewrite your model to be :
public class LOCR
{
public LOCR_Error error { get; set; }
// object here since "data": { ... }
public LOCR_Data data { get; set; }
}
And as you move further with the JSON you can see that LOCR_Data.country is in fact an array in both cases "country": [ ... ] so you can stick with the current implementation of LOCR_Data class.
Try Using :
YourResultClass object = JsonConvert.DeserializeObject<YourResultClass>(Jsonstring);
See the answer of this Using JsonConvert.DeserializeObject to deserialize Json
OR
dynamic data = Json.Decode(json);
You can refer this Deserialize JSON into C# dynamic object? for further assistance
I'm getting the following error when trying to deserliaze my JSON into a Dictionary<string, Resources>[]:
An unhandled exception of type
'Newtonsoft.Json.JsonSerializationException' occurred in
Newtonsoft.Json.dll
Additional information: Cannot deserialize the current JSON object
(e.g. {"name":"value"}) into type
'System.Collections.Generic.Dictionary`2[System.String,MyProject.Resource][]'
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.
My Program.Main():
public class Program
{
public static void Main(string[] Args)
{
var options = new Options()
{
Option1 = "foo",
Option2 = "bar",
Resources = JsonConvert.DeserializeObject<Dictionary<string, Resource>[]>(resources.json)
};
}
}
My resources.json:
{
"global": [
{
"title": "global1",
"url": "~/global1"
},
{
"title": "global2",
"url": "~/global2"
}
],
"ACC": [
{
"title": "acc1",
"url": "~/acc1/"
},
{
"title": "acc2",
"url": "~/acc2/"
}
],
"ECC": [
{
"title": "ecc1",
"url": "~/ecc1/"
},
{
"title": "ecc2",
"url": "~/ecc2/"
}
],
"ECB": [
{
"title": "ecb1",
"url": "~/ecb1"
}
]
}
My Resource class:
public class Resource
{
public List<string> titles { get; set; }
public List<string> urls { get; set; }
}
My Options class:
public class Options
{
public string Option1 { get; set; }
public string Option2 { get; set; }
public Dictionary<string, Resource>[] Resources { get; set; }
}
Your JSON does not represent an array of dictionaries (Dictionary<string, Resource>[]), it represents a dictionary of arrays (Dictionary<string, Resource[]>). That is why you are getting the error.
Also, your Resource class needs to be defined like this to match the JSON:
public class Resource
{
public string Title { get; set; }
public string Url { get; set; }
}
You can then deserialize like this:
Resources = JsonConvert.DeserializeObject<Dictionary<string, Resource[]>>(resources.json)
See fiddle here: https://dotnetfiddle.net/8s2eQd
Your Json doesn't match up with your class structure.
If you want to keep your class structure your json has to look like this:
{
"global":{
"titles":[
"global1",
"global2"
],
"urls":[
"~/global1",
"~/global2"
]
},
"acc":{
"titles":[
"acc1",
"acc2"
],
"urls":[
"~/acc1",
"~/acc2"
]
},
...
}
If you can't influence your json file (for what ever reason) your class structure has to look like this:
public class Rootobject
{
public Global[] global { get; set; }
public ACC[] ACC { get; set; }
public ECC[] ECC { get; set; }
public ECB[] ECB { get; set; }
}
public class Global
{
public string title { get; set; }
public string url { get; set; }
}
public class ACC
{
public string title { get; set; }
public string url { get; set; }
}
public class ECC
{
public string title { get; set; }
public string url { get; set; }
}
public class ECB
{
public string title { get; set; }
public string url { get; set; }
}
Then you can deserialize it like this:
Resources = JsonConvert.DeserializeObject<Rootobject>(resources.json)
Little note for the next time:
If you are not sure how your class structure has to look like (regarding to a json string), you can copy the json string and go to:
Visual Studio -> Edit -> Paste Special -> Paste JSON as Classes
and Visual Studio will make up the appropriate class structure.
I'm having a bit of a problem with serializing my .NET objects into JSON using JSON.NET. The output I want to be serialized will have to look like this:
{"members":[
{"member":
{
"id":"4282",
"status":"1931",
"aktiv":"1",
"firmanavn":"firmname1",
"firmaUrl":"www.firmurl.dk",
"firmaUrlAlternativ":"",
"firmaSidstKontrolleretDato":"30-08-2010",
"firmaGodkendelsesDato":"07-03-2002"
}
},
{"member":
{
"id":"4283",
"status":"1931",
"aktiv":"1",
"firmanavn":"firmname2",
"firmaUrl":"www.firmurl.dk",
"firmaUrlAlternativ":"",
"firmaSidstKontrolleretDato":"30-08-2010",
"firmaGodkendelsesDato":"18-12-2000"
}
},
...... long list of members omitted
My .NET structure for now (still experimenting to get the right output) is like this:
public class Members
{
public List<Member> MemberList { get; set; }
}
and:
public class Member
{
[JsonProperty(PropertyName = "Id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "Status")]
public string Status { get; set; }
[JsonProperty(PropertyName = "Aktiv")]
public string Aktiv { get; set; }
[JsonProperty(PropertyName = "Firmanavn")]
public string Firmanavn { get; set; }
[JsonProperty(PropertyName = "FirmaUrl")]
public string FirmaUrl { get; set; }
[JsonProperty(PropertyName = "AltFirmaUrl")]
public string AlternativFirmaUrl { get; set; }
[JsonProperty(PropertyName = "FirmaSidstKontrolleretDato")]
public string FirmaSidstKontrolleretDato { get; set; }
[JsonProperty(PropertyName = "FirmaGodkendelsesDato")]
public string FirmaGodkendelsesDato { get; set; }
}
What the above .NET structure gives me when calling:
string json = JsonConvert.SerializeObject(members, Newtonsoft.Json.Formatting.Indented);
Where 'members' is a list of members. Is this:
{
"Members": [
{
"Id": "1062",
"Status": "1933",
"Aktiv": "1",
"Firmanavn": "firmname",
"FirmaUrl": "http://www.firmurl.dk",
"AltFirmaUrl": "http://www.altfirmurl.dk",
"FirmaSidstKontrolleretDato": "13-09-2011",
"FirmaGodkendelsesDato": "13-09-2511"
},
{
"Id": "1060",
"Status": "1933",
"Aktiv": "1",
"Firmanavn": "firmname2",
"FirmaUrl": "http://www.firmurl.dk",
"AltFirmaUrl": "http://www.altfirmurldk",
"FirmaSidstKontrolleretDato": "13-09-2011",
"FirmaGodkendelsesDato": "13-09-2511"
},
So basically, the structure is right in that it creates the array of members as expected, but I am missing the "member": label on each of the member objects. Is there any way to make such a label? Some kind of class declaration, or something?
I hope my question is clear, if not - please let me know and I'll try to explain further.
Thanks a lot in advance.
/ Bo
It sounds like you just need to make an intermediary object with a property of that name to get the JSON you want; however, I'd consider using the JSON.net originally rendered JSON (as it is structurally better).