JSON C# deserialization - c#

I am having trouble with deserializing data from a JSON string:
[{
"Example A": [{
"Parameter1": "Example A",
"Parameter2": "aaa",
"Parameter3": "2022-06-30 21:15:00.0000000",
"Value": 11.11
}
],
"Example B": [{
"Parameter1": "Example B",
"Parameter2": "ccc",
"Parameter3": "2022-06-30 21:15:00.0000000",
"Value": 33.33
}
],
"Example C": [
{
"Parameter1": "Example C",
"Parameter2": "eee",
"TimestampUTC": "2022-06-30 21:15:00.0000000",
"Value": null
},
{
"Parameter1": "Example C",
"Parameter2": "fff",
"Parameter3": "2022-06-30 21:15:00.0000000",
"Value": 44.44
}
]
}]
What I have tried is:
public class ExampleA
{
public string Parameter1 { get; set; }
public string Parameter2 { get; set; }
public string Parameter3 { get; set; }
public double Value { get; set; }
}
public class ExampleB
{
public string Parameter1 { get; set; }
public string Parameter2 { get; set; }
public string Parameter3 { get; set; }
public double Value { get; set; }
}
public class ExampleC
{
public string Parameter1 { get; set; }
public string Parameter2 { get; set; }
public string Parameter3 { get; set; }
public double Value { get; set; }
}
public class Examples
{
[JsonProperty("Example A")]
public List<ExampleA> ExampleA { get; set; }
[JsonProperty("Example B")]
public List<ExampleB> ExampleB { get; set; }
[JsonProperty("Example C")]
public List<ExampleC> ExampleC { get; set; }
}
But when I try to test it with this:
Examples someVar = JsonConvert.DeserializeObject<Examples>(JsonString);
Console.WriteLine(SomeVar.ExampleA.Count);
I get this error:
Unhandled exception. Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'MyProject.Examples' 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<T> 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.
Apparently I have trouble understanding how deserialization works - what I want to do with this is something like this:
foreach item in Example
// do something
foreach thing in item
// do something more
I realise I have some trouble with grasping the JSON format in this case.
I'm using .NET Core.

you have an array in your json Try this
List<Examples> someVar = JsonConvert.DeserializeObject<List<Examples>>(JsonString);

Related

How to deserialise this nested json response and save the the array values with multiple Jobjects (in Unity)

I have little to no experience in JSON and I am stuck with a problem. Any help is appreciated.
I want to access specifically the names' values from the additionalInformation array.
JSON Response:
{
"statusCode": 200,
"version": 1,
"jsonData": [
{
"additionalInformation": [
{
"id": "XXX94XXXX9xxXx_xxxXXXX",
"name": "xxxx xxx x xxxxxxxx"
},
{
"id": "0xXXxcXxv5PQqT$6i2zLgV",
"name": "xxx xxxxxxxx"
},
{
"id": "11Krt_our2rPCPqJ_2fKZR",
"name": "xxx xxxxxxxx xx"
},
{
"id": "2jYw4IyBP8KuozM_ej7DGf",
"name": "xxxxxxx 1"
},
{
"id": "3B8O805wL1ufabHMz1Je3v",
"name": "xxxxxxx 2"
},
{
"id": "0FVKUYZkvFaxd_OQUiyPBZ",
"name": "xxxxxxx"
},
{
"id": "3O41QFd0573QQvFco5zUUP",
"name": "Xxxxxxxxx"
}
],
"type": 0
}
],
"errorMessages": [],
"warningMessages": [],
"informationMessages": []
}
Model:
public class CFunctions
{
public int statusCode { get; set; }
public int version { get; set; }
public List<PFunctions>[] jsonData { get; set; }
public List<string> errorMessages { get; set; }
public List<string> warningMessages { get; set; }
public List<string> informationMessages { get; set; }
/*public CFunctions()
{
jsonData = new List<PFunctions>();
}*/
}
[Serializable]
public class PFunctions
{
public List<PAdditionalInfo>[] additionalInformation { get; set; }
public int type { get; set; }
/*public PFunctions()
{
additionalInformation = new List<PAdditionalInfo>();
}*/
}
[Serializable]
public class PAdditionalInfo
{
public Guid id { get; set; }
public string name { get; set; }
}
Deserialisation
var request = UnityWebRequest.Get(baseurl);
var operation = request.SendWebRequest();
var jsonResponse = request.downloadHandler.text;
List<CFunctions>[] PFunctionsList = JsonConvert.DeserializeObject<List<CFunctions>[]>(jsonResponse);
Error:
Cannot deserialize the current JSON object into type 'System.Collections.Generic.List`1[CFunctions][]' because the type requires a JSON array to deserialize correctly.
To fix this error either change the JSON to a JSON array or change the deserialized type so that it is a normal .NET type 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 'statusCode', line 1, position 14.
UnityEngine.Debug:Log(Object)
What I tried
The error pertains even when I changed List<PAdditionalInfo> to List<PAdditionalInfo>[]
I am not sure how to use JsonObjectAttribute and if it is the best way.
You've declared an array of List<T> in the models, eg List<PAdditionalInfo>[]. The json represents single arrays, not nested. You can fix that by choosing one or the other (I decided to use List<> but array is valid too):
public class PFunctions
{
public List<PAdditionalInfo> additionalInformation { get; set; } // removed []
...
}
public class CFunctions
{
public int statusCode { get; set; }
public int version { get; set; }
public List<PFunctions> jsonData { get; set; } // removed []
...
}
The class you're deserializing to is incorrect. Deserialize to the correct type (which is CFunctions not List<CFunctions>[]):
CFunctions cFunctions = JsonConvert.DeserializeObject<CFunctions>(json);
the most efficient way to get an additional information is this one line code and you only need one class
List<AdditionalInformation> additionalInformation = JObject.Parse(json)
["jsonData"][0]["additionalInformation"].ToObject<List<AdditionalInformation>>();
class
public class AdditionalInformation
{
public string id { get; set; }
public string name { get; set; }
}

Json.JsonSerializationException : Cannot deserialize the current JSON object

My problem is that I'm getting this error when I try to deserialize my API json response.
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Entities.JsonDataType]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
My json data return something like this
{
"success": true,
"result": [
{
"name": "USD Amerikan Doları",
"buying": "6.6920",
"selling": "6.6995"
},
{
"name": "EUR Euro",
"buying": "7.7322",
"selling": "7.7393"
},
{
"name": "GBP İngiliz Sterlini",
"buying": "8.5933",
"selling": "8.6041"
},
"..."
]
}
My class properties:
public class JsonDataType
{
//public string name { get; set; }
//public string buying { get; set; }
//public string selling { get; set; }
public bool success { get; set; }
public List<Result> result { get; set; }
}
public class Result
{
public string name { get; set; }
public string buying { get; set; }
public string selling { get; set; }
}
And I'm getting the error when I deserialize:
List<JsonDataType> X = Newtonsoft.Json.JsonConvert.DeserializeObject<List<JsonDataType>>(response.Content);
Also I tried these codes but none of them working
JsonDataType X = JsonConvert.DeserializeObject(response.Content);
IEnumerable<Result> X = (JsonDataType)JsonConvert.DeserializeObject<IEnumerable<Result>>(response.Content, typeof(JsonDataType));
List<Result> X = JsonConvert.DeserializeObject<JsonDataType>(response.Content, typeof(Result));
If someone could help me i will be so peaceful.
Thanks for your time in advance (✿◠‿◠)
Here is my answer
JsonDataType X = Newtonsoft.Json.JsonConvert.DeserializeObject<JsonDataType>(response.Content);

Nested List property causing problems when deserializing in C#

I have spent all day referencing numerous posts and trying all sorts of different techniques for resolving this issue, to no avail. My failures may just be the result of a lack of understanding, but I have never experienced this kind of problem before so I have arrived at something of an impasse.
Given the following JSON as a string received from a WebService request ...
{
"contacts": [{
"identities": [{
"vid": 40451,
"identity": [{
"value": "bsmith#aol.com",
"type": "EMAIL",
"timestamp": 4556668881236,
"isPrimary": true
},
{
"value": "a2c53333-3333-3333-3333-34bc21723333",
"type": "LEAD_GUID",
"timestamp": 4556668881236
}],
"linkedVid": []
}],
"properties": [{
"name": "firstname",
"value": "Bob",
"sourceVid": []
},
{
"name": "lastmodifieddate",
"value": "151512112212",
"sourceVid": []
},
{
"name": "lastname",
"value": "Smith",
"sourceVid": []
}],
"formSubmissions": [],
"listMembership": [],
"vid": 44444,
"portalId": 4444444,
"isContact": true,
"vids": [],
"imports": [],
"publicToken": "kshdfkjhsdsdjfjkdhshjksd",
"canonicalVid": 44444,
"mergeAudit": [],
"mergedVids": [],
"campaigns": [],
"stateChanges": []
}, {
...
}, {
...
}]
}
When I try to deserialize the list of contacts ...
String jsonString = obj.GetJson();
var response = Newtonsoft.Json.JsonConvert.DeserializeObject<HSContactListResult>(
jsonString,
new Newtonsoft.Json.JsonSerializerSettings
{
TypeNameHandling = Newtonsoft.Json.TypeNameHandling.All,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore
});
I get the error message ...
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'HSContactIdentityProfile' 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<T> 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 'contacts[0].identities', line 1, position 28
The following classes represent the which the JSON is deserialized into ...
[Serializable]
[DataContract]
public class HSContactListResult
{
[DataMember(Name ="hasMore")]
public bool HasMore { get; set; }
[DataMember(Name = "vidOffset")]
public long Offset { get; set; }
[DataMember(Name = "contacts")]
public List<Companies.Models.HSContact> Contacts{ get; set; }
public Int32 Count { get { return this.Contacts.Count; } }
public HSContactListResult()
{
this.Contacts = new List<Companies.Models.HSContact>().ToList();
}
}
[Serializable]
[DataContract]
public class HSContact
{
[DataMember(Name = "vid")]
public long ContactId { get; set; }
[DataMember(Name = "portalId")]
public long PortalId { get; set; }
[DataMember(Name = "isContact")]
public bool IsContact { get; set; }
[DataMember(Name = "properties")]
public Companies.Models.HSContactProperties Properties { get; set; }
[DataMember(Name = "identities")]
public Companies.Models.HSContactIdentityProfile IdentityProfiles { get; }
public HSCompany Company { get; set; }
#region c-tor
public HSContact()
{
this.Properties = new Companies.Models.HSContactProperties();
this.IdentityProfiles = new Companies.Models.HSContactIdentityProfile();
}
#endregion c-tor
}
[Serializable]
[DataContract]
public class HSContactProperties: IHSContactProperties
{
[DataMember(Name ="firstname")]
public HSProperty FirstName { get; set; }
[DataMember(Name = "lastname")]
public HSProperty LastName { get; set; }
[DataMember(Name = "company")]
public HSProperty CompanyName { get; set; }
}
[Serializable]
[DataContract]
public class HSContactIdentityProfile
{
[DataMember(Name = "vid")]
public Int64 ContactID { get; set; }
[DataMember(Name = "identity")]
public List<Companies.Models.HSContactIdentity> Identities { get; set; }
[DataMember(Name = "saved-at-timestamp")]
public Int64 saved_at_timestamp { get; set; }
[DataMember(Name = "deleted-changed-timestamp")]
public Int64 deleted_changed_timestamp { get; set; }
public HSContactIdentityProfile()
{
this.Identities = new List<Companies.Models.HSContactIdentity>().ToList();
}
}
[Serializable]
[DataContract]
public class HSContactIdentity : IHSContactIdentity
{
[DataMember(Name = "type")]
public string Type { get; set; }
[DataMember(Name = "value")]
public string Value { get; set; }
[DataMember(Name = "timestamp")]
public long Timestamp { get; set; }
[DataMember(Name = "isPrimary")]
public bool IsPrimary { get; set; }
}
The problem appears to be that Newtonsoft wants to deserialize the HSContactIdentityProfile instance into an Array even though it's actually an object. The property "Identities" IS an array and since it seems to be cvalled out I am assuming that that is interfering with the desrialization process. I don't understand however why it's just not deserializing the List as a property of the HSContactIdentityProfile object.
I have tried custom converters but may have done those incorrectly (first time with this). I am not sure what else to try.
After trying to implement 5 or 6 of the "fixes" presented in other potential duplicate posts I have not been able to resolve it.
As per the error message:
[DataMember(Name = "identities")]
public Companies.Models.HSContactIdentityProfile IdentityProfiles { get; }
should be a list or array:
[DataMember(Name = "identities")]
public List<Companies.Models.HSContactIdentityProfile> IdentityProfiles { get; }
Your original code would work if the original JSON was:
"contacts": {
"identities"
but alas it is "contacts": [{
"identities"
(the extra [ meaning a JSON array is involved)

Unusual Deserialization Error from JSON to C#

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

Deserialize a list of objects from Json Http response

I have my JSON Response like that:
{
"Adddress": [
{
"Country": "United States",
"City": "Irmo",
"Line1": "103 Kinley Rd",
"Line2": null,
"PostalCode": "20063",
"State": "SC",
"AddressCode": "BILL-01"
},
{
"Country": "United States",
"City": "Irmo",
"Line1": "1098 Kanley Road",
"Line2": "Building B",
"PostalCode": "29063",
"State": "SC",
"AddressCode": "SHIP-01"
}]
}
َAnd Here is my Address Class:
[JsonObject()]
public class Address
{
public string AddressCode { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Country { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public string City { get; set; }
}
And I have this C# Code to deserialize this http response to my object list:
HttpResponseMessage response = client.GetAsync(urlParameters).Result; // Blocking call!
if (response.IsSuccessStatusCode)
{
var dataObjects = response.Content.ReadAsAsync<Adddress>().Result;//JsonConvert.DeserializeObject<List<RestResponse>>(response.Content.ReadAsStringAsync().Result);//
foreach (var d in dataObjects)
{
Console.WriteLine("{0}", d.Country);
}
}
But I'm getting this error:
Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.IEnumerable`1[TestREST.Program+RestResponse]' 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 'RestResponse', line 2, position 19.
What should I do with it to make my deserilization work ?
Adddress is single, the json you get in is an array of addresses (so more then one), you have to deserialize it into e.g. AddressList that contains more then one address
string json = "{\"Adddress\":[{\"Country\":\"United States\",\"City\":\"Irmo\",\"Line1\":\"103 Kinley Rd\",\"Line2\":null,\"PostalCode\":\"20063\",\"State\":\"SC\",\"AddressCode\":\"BILL - 01\"},{\"Country\":\"United States\",\"City\":\"Irmo\",\"Line1\":\"1098 Kanley Road\",\"Line2\":\"Building B\",\"PostalCode\":\"29063\",\"State\":\"SC\",\"AddressCode\":\"SHIP - 01\"}]}";
var dataObjects = JsonConvert.DeserializeObject<AddressList>(json);
foreach (var d in dataObjects.Adddress)
{
Console.WriteLine("{0}", d.Country);
}
Classes:
public class Adddress
{
[JsonProperty("Country")]
public string Country { get; set; }
[JsonProperty("City")]
public string City { get; set; }
[JsonProperty("Line1")]
public string Line1 { get; set; }
[JsonProperty("Line2")]
public string Line2 { get; set; }
[JsonProperty("PostalCode")]
public string PostalCode { get; set; }
[JsonProperty("State")]
public string State { get; set; }
[JsonProperty("AddressCode")]
public string AddressCode { get; set; }
}
public class AddressList
{
[JsonProperty("Adddress")]
public IList<Adddress> Adddress { get; set; }
}

Categories