How can I deserialize JSON with C#? - c#

I have the following JSON string:
string jsonData = #"{""type"":""address"",""found objects"":9,""returned objects"":9,""results"":{""1"":{""city"":""Ceg\u0142\u00f3w"",""citypart"":null,""street"":""Adama Asnyka"",""number"":""11"",""teryt"":""141204"",""simc"":""0668956"",""ulic"":""00470"",""code"":""05 - 319"",""jednostka"":""{ Polska,mazowieckie,mi\u0144ski,Ceg\u0142\u00f3w}
"",""x"":""688066.62"",""y"":""479206.44"",""geometry_wkt"":""POINT(688066.62 479206.44)"",""id"":1},""2"":{""city"":""Ceg\u0142\u00f3w"",""citypart"":null,""street"":""Adama Asnyka"",""number"":""13A"",""teryt"":""141204"",""simc"":""0668956"",""ulic"":""00470"",""code"":""05 - 319"",""jednostka"":""{ Polska,mazowieckie,mi\u0144ski,Ceg\u0142\u00f3w}
"",""x"":""688081.88"",""y"":""479250.24"",""geometry_wkt"":""POINT(688081.88 479250.24)"",""id"":2},""3"":{""city"":""Ceg\u0142\u00f3w"",""citypart"":null,""street"":""Adama Asnyka"",""number"":""15"",""teryt"":""141204"",""simc"":""0668956"",""ulic"":""00470"",""code"":""05 - 319"",""jednostka"":""{ Polska,mazowieckie,mi\u0144ski,Ceg\u0142\u00f3w}
"",""x"":""688126.5"",""y"":""479229.34"",""geometry_wkt"":""POINT(688126.5 479229.34)"",""id"":3},""4"":{""city"":""Ceg\u0142\u00f3w"",""citypart"":null,""street"":""Adama Asnyka"",""number"":""18"",""teryt"":""141204"",""simc"":""0668956"",""ulic"":""00470"",""code"":""05 - 319"",""jednostka"":""{ Polska,mazowieckie,mi\u0144ski,Ceg\u0142\u00f3w}
"",""x"":""688179.59"",""y"":""479255.470000001"",""geometry_wkt"":""POINT(688179.59 479255.470000001)"",""id"":4},""5"":{""city"":""Ceg\u0142\u00f3w"",""citypart"":null,""street"":""Adama Asnyka"",""number"":""4"",""teryt"":""141204"",""simc"":""0668956"",""ulic"":""00470"",""code"":""05 - 319"",""jednostka"":""{ Polska,mazowieckie,mi\u0144ski,Ceg\u0142\u00f3w}
"",""x"":""688021.03"",""y"":""479167.77"",""geometry_wkt"":""POINT(688021.03 479167.77)"",""id"":5},""6"":{""city"":""Ceg\u0142\u00f3w"",""citypart"":null,""street"":""Adama Asnyka"",""number"":""6"",""teryt"":""141204"",""simc"":""0668956"",""ulic"":""00470"",""code"":""05 - 319"",""jednostka"":""{ Polska,mazowieckie,mi\u0144ski,Ceg\u0142\u00f3w}
"",""x"":""688073.16"",""y"":""479175.42"",""geometry_wkt"":""POINT(688073.16 479175.42)"",""id"":6},""7"":{""city"":""Ceg\u0142\u00f3w"",""citypart"":null,""street"":""Adama Asnyka"",""number"":""6A"",""teryt"":""141204"",""simc"":""0668956"",""ulic"":""00470"",""code"":""05 - 319"",""jednostka"":""{ Polska,mazowieckie,mi\u0144ski,Ceg\u0142\u00f3w}
"",""x"":""688063.45"",""y"":""479133.4"",""geometry_wkt"":""POINT(688063.45 479133.4)"",""id"":7},""8"":{""city"":""Ceg\u0142\u00f3w"",""citypart"":null,""street"":""Adama Asnyka"",""number"":""6B"",""teryt"":""141204"",""simc"":""0668956"",""ulic"":""00470"",""code"":""05 - 319"",""jednostka"":""{ Polska,mazowieckie,mi\u0144ski,Ceg\u0142\u00f3w}
"",""x"":""688072.54"",""y"":""479095.720000001"",""geometry_wkt"":""POINT(688072.54 479095.720000001)"",""id"":8},""9"":{""city"":""Ceg\u0142\u00f3w"",""citypart"":null,""street"":""Adama Asnyka"",""number"":""8B"",""teryt"":""141204"",""simc"":""0668956"",""ulic"":""00470"",""code"":""05 - 319"",""jednostka"":""{ Polska,mazowieckie,mi\u0144ski,Ceg\u0142\u00f3w}
"",""x"":""688110.78"",""y"":""479085.880000001"",""geometry_wkt"":""POINT(688110.78 479085.880000001)"",""id"":9}},""request time"":0.027953267097473145}";
and code:
jsonAddresses _jsonAddresses = JsonConvert.DeserializeObject<jsonAddresses>(jsonData);
[System.Serializable]
public class jsonAddresses
{
[JsonProperty(PropertyName = "type")]
public string type { get; set; }
[JsonProperty(PropertyName = "found objects")]
public string foundobjects { get; set; }
[JsonProperty(PropertyName = "returned objects")]
public string returnedobjects { get; set; }
[JsonProperty(PropertyName = "results")]
public IList<jsonResults> results { get; set; }
}
[System.Serializable]
public class jsonResults
{
[JsonProperty(PropertyName = "city")]
public string city { get; set; }
[JsonProperty(PropertyName = "citypart")]
public string citypart { get; set; }
[JsonProperty(PropertyName = "street")]
public string street { get; set; }
[JsonProperty(PropertyName = "number")]
public string number { get; set; }
[JsonProperty(PropertyName = "teryt")]
public string teryt { get; set; }
[JsonProperty(PropertyName = "simc")]
public string simc { get; set; }
[JsonProperty(PropertyName = "ulic")]
public string ulic { get; set; }
[JsonProperty(PropertyName = "code")]
public string code { get; set; }
[JsonProperty(PropertyName = "jednostka")]
public string jednostka { get; set; }
[JsonProperty(PropertyName = "x")]
public string x { get; set; }
[JsonProperty(PropertyName = "y")]
public string y { get; set; }
[JsonProperty(PropertyName = "geometry_wkt")]
public string geometry_wkt { get; set; }
[JsonProperty(PropertyName = "id")]
public string id { get; set; }
}
I have problem with deserialize object with list of objects. I think the problem is in the wrong class of the object being in the list, but I don't know which one.
ERROR: Newtonsoft.Json.JsonSerializationException: „Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.IList`1[DeserializeJSON.jsonResults]' 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 'results.1', line 1, position 72.”
How should I properly deserialize it?

you have to fix the jsonAddresses class, change a list to a dictionary, for example
[JsonProperty(PropertyName = "results")]
public Dictionary<string,jsonResults> results { get; set; }
or if you want the list
public class jsonAddresses
{
[JsonProperty(PropertyName = "type")]
public string type { get; set; }
[JsonProperty(PropertyName = "found objects")]
public string foundobjects { get; set; }
[JsonProperty(PropertyName = "returned objects")]
public string returnedobjects { get; set; }
public IList<jsonResults> results { get; set; }
[JsonConstructor]
public jsonAddresses (JObject results)
{
this.results= results.Properties().Select(x => x.Value.ToObject<jsonResults>() ).ToList();
}
}

It helps to view the JSON string in a nicer or "pretty" view:
string jsonData = #"{
"type":"address",
"found objects":9,
"returned objects":9,
"results":{
"1":{
"city":"Ceg\u0142\u00f3w",
"citypart":null,
"street":"Adama Asnyka",
"number":"11",
"teryt":"141204",
"simc":"0668956",
"ulic":"00470",
"code":"05 - 319",
"jednostka":"{ Polska,mazowieckie,mi\u0144ski,Ceg\u0142\u00f3w}",
"x":"688066.62",
"y":"479206.44",
"geometry_wkt":"POINT(688066.62 479206.44)",
"id":1
},
"2":{
"city":"Ceg\u0142\u00f3w",
"citypart":null,
...
}
}
};
Now you can see that the "results" element is not an array. If it were an array, it would be wrapped in []. Instead, "results" is just a JSON object with key value pairs. Each key value pair is "number":{another JSON object}. Either change your JSON structure, or as #Serge suggests, change your C# a bit to properly handle the key value pairs.

Related

C# Newtonsoft JsonSerializationException when deserializing a serialized string

I must be making a stupid mistake. When I run:
JsonResponse testREsponse = new JsonResponse
{
StartTimeUtc = 1,
EndTimeUtc = 1,
TimeResolutionInMilliseconds = 60000,
Results = new JsonResults
{
Type = "hello",
Values = new List<EvaluatedResult>()
}
};
string convertTest = JsonConvert.SerializeObject(testREsponse);
Console.WriteLine("HRMM " + convertTest);
JsonResponse jsonResponse = JsonConvert.DeserializeObject<JsonResponse>(convertTest);
I'm getting a
Unhandled Exception: Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'JarvisReader.JsonResults' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
when trying to deserialize a string that I serialized the line above. It's indicating 'Path 'results.$values', line 1, position 71.' which would be the results bracket.
Objects:
class JsonResponse
{
[JsonProperty("startTimeUtc")]
public long StartTimeUtc { get; set; }
[JsonProperty("endTimeUtc")]
public long EndTimeUtc { get; set; }
[JsonProperty("results")]
public JsonResults Results { get; set; }
[JsonProperty("timeResolutionInMilliseconds")]
public int TimeResolutionInMilliseconds { get; set; }
}
class JsonResults
{
[JsonProperty("$type")]
public string Type { get; set; }
[JsonProperty("$values")]
public List<EvaluatedResult> Values { get; set; }
}
class EvaluatedResult
{
[JsonProperty("dimensionList")]
public DimensionList dimensionList { get; set; }
[JsonProperty("evaluatedResult")]
public decimal evaluatedResult { get; set; }
[JsonProperty("seriesValues")]
public List<Decimal> seriesValues { get; set; }
}
class DimensionList
{
[JsonProperty("$type")]
public string type { get; set; }
[JsonProperty("$values")]
public List<Dimension> values;
}
class Dimension
{
[JsonProperty("key")]
public string key { get; set; }
[JsonProperty("value")]
public string value { get; set; }
}
I condensed my testREsponse to be almost empty. And it looks like it serializes just fine.
{"startTimeUtc":1,"endTimeUtc":1,"results":{"$type":"hello","$values":[]},"timeResolutionInMilliseconds":60000}
When I remove JsonResults from the construction, it serializes and deserializes just fine. What am I missing? Thanks in advance.
Try the following:
JsonConvert.DeserializeObject<JsonResponse>(convertTest, new JsonSerializerSettings { MetadataPropertyHandling = MetadataPropertyHandling.Ignore });
$ indicates metadata. The serializer setting makes the value get treated like a property.

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

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List

I have the following code
public async Task<ActionResult> GetExtendedProperties()
{
Uri serviceRoot = new Uri(SettingsHelper.AzureAdGraphApiEndPoint);
var token = AppToken.GetAppToken();
var adClient = AuthenticationHelper.GetActiveDirectoryClient();
Microsoft.Azure.ActiveDirectory.GraphClient.Application app = (Microsoft.Azure.ActiveDirectory.GraphClient.Application)adClient.Applications.Where(
a => a.AppId == SettingsHelper.ClientId).ExecuteSingleAsync().Result;
if (app == null)
{
throw new ApplicationException("Unable to get a reference to application in Azure AD.");
}
string requestUrl = string.Format("https://graph.windows.net/{0}/applications/{1}/extensionProperties?api-version=1.5", SettingsHelper.Tenant, app.ObjectId);
HttpClient hc = new HttpClient();
hc.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(
"Bearer", token);
HttpResponseMessage hrm = await hc.GetAsync(new Uri(requestUrl));
if (hrm.IsSuccessStatusCode)
{
string jsonresult = await hrm.Content.ReadAsStringAsync();
return View();
}
else
{
return View();
}
}
and it returns this string
{"odata.metadata":"https://graph.windows.net/mysaasapp.onmicrosoft.com/$metadata#directoryObjects/Microsoft.DirectoryServices.ExtensionProperty","value":[{"odata.type":"Microsoft.DirectoryServices.ExtensionProperty","objectType":"ExtensionProperty","objectId":"f751a646-2cc1-4e30-bfc6-a8217c0ce0a3","deletionTimestamp":null,"appDisplayName":"","name":"extension_33e037a7b1aa42ab96936c22d01ca338_Modulos","dataType":"String","isSyncedFromOnPremises":false,"targetObjects":["User"]},{"odata.type":"Microsoft.DirectoryServices.ExtensionProperty","objectType":"ExtensionProperty","objectId":"80aabe1b-b020-41d1-bd2d-cc04af264fe5","deletionTimestamp":null,"appDisplayName":"","name":"extension_33e037a7b1aa42ab96936c22d01ca338_ModulesPerUser","dataType":"String","isSyncedFromOnPremises":false,"targetObjects":["User"]},{"odata.type":"Microsoft.DirectoryServices.ExtensionProperty","objectType":"ExtensionProperty","objectId":"6e3d7592-7a66-4792-b408-891251197868","deletionTimestamp":null,"appDisplayName":"","name":"extension_33e037a7b1aa42ab96936c22d01ca338_Comasdasa3dsdaspInfo","dataType":"String","isSyncedFromOnPremises":false,"targetObjects":["User"]},{"odata.type":"Microsoft.DirectoryServices.ExtensionProperty","objectType":"ExtensionProperty","objectId":"93a26374-4135-4f29-9f24-4154522449ec","deletionTimestamp":null,"appDisplayName":"","name":"extension_33e037a7b1aa42ab96936c22d01ca338_CompInfo","dataType":"String","isSyncedFromOnPremises":false,"targetObjects":["User"]},{"odata.type":"Microsoft.DirectoryServices.ExtensionProperty","objectType":"ExtensionProperty","objectId":"21a8a3d4-f4b4-45b4-8d07-55d450db35f2","deletionTimestamp":null,"appDisplayName":"","name":"extension_33e037a7b1aa42ab96936c22d01ca338_CompanyNameForSaasApp","dataType":"String","isSyncedFromOnPremises":false,"targetObjects":["User"]},{"odata.type":"Microsoft.DirectoryServices.ExtensionProperty","objectType":"ExtensionProperty","objectId":"7b3109e0-8710-4d1a-81c3-2b6a83fb62ee","deletionTimestamp":null,"appDisplayName":"","name":"extension_33e037a7b1aa42ab96936c22d01ca338_Compania","dataType":"String","isSyncedFromOnPremises":false,"targetObjects":["User"]}]}
Using json2charp, I created this class:
public class ActiveDirectorySchemaExtension
{
public string objectType { get; set; }
public string objectId { get; set; }
public object deletionTimestamp { get; set; }
public string appDisplayName { get; set; }
public string name { get; set; }
public string dataType { get; set; }
public bool isSyncedFromOnPremises { get; set; }
public List<string> targetObjects { get; set; }
}
How can I convert that string into a List so that I can easy manipulate it on the view?
Update:
I tried this:
List<ActiveDirectorySchemaExtension> tmp = JsonConvert.DeserializeObject<List<ActiveDirectorySchemaExtension>>(jsonresult);
but I got this
Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type
'System.Collections.Generic.List`1[CapatechSaasApp.Areas.GlobalAdmin.Models.ActiveDirectorySchemaExtension]'
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 '['odata.metadata']', line 1,
position 18.
You forgot your parent object in json2csharp.
Demo on .NETFiddle
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class ActiveDirectorySchemaExtension // You can switch from the original class name to yours
{
public string Type { get; set; } // You should switch to PascalCase to respect C# notation
public string ObjectType { get; set; }
public string ObjectId { get; set; }
public object DeletionTimestamp { get; set; }
public string AppDisplayName { get; set; }
public string Name { get; set; }
public string DataType { get; set; }
public bool IsSyncedFromOnPremises { get; set; }
public List<string> TargetObjects { get; set; }
}
public class RootObject
{
public string Metadata { get; set; }
public List<ActiveDirectorySchemaExtension> Value { get; set; }
}
public void Main()
{
var json = "{'odata.metadata':'https://graph.windows.net/mysaasapp.onmicrosoft.com/$metadata#directoryObjects/Microsoft.DirectoryServices.ExtensionProperty','value':[{'odata.type':'Microsoft.DirectoryServices.ExtensionProperty','objectType':'ExtensionProperty','objectId':'f751a646-2cc1-4e30-bfc6-a8217c0ce0a3','deletionTimestamp':null,'appDisplayName':'','name':'extension_33e037a7b1aa42ab96936c22d01ca338_Modulos','dataType':'String','isSyncedFromOnPremises':false,'targetObjects':['User']},{'odata.type':'Microsoft.DirectoryServices.ExtensionProperty','objectType':'ExtensionProperty','objectId':'80aabe1b-b020-41d1-bd2d-cc04af264fe5','deletionTimestamp':null,'appDisplayName':'','name':'extension_33e037a7b1aa42ab96936c22d01ca338_ModulesPerUser','dataType':'String','isSyncedFromOnPremises':false,'targetObjects':['User']},{'odata.type':'Microsoft.DirectoryServices.ExtensionProperty','objectType':'ExtensionProperty','objectId':'6e3d7592-7a66-4792-b408-891251197868','deletionTimestamp':null,'appDisplayName':'','name':'extension_33e037a7b1aa42ab96936c22d01ca338_Comasdasa3dsdaspInfo','dataType':'String','isSyncedFromOnPremises':false,'targetObjects':['User']},{'odata.type':'Microsoft.DirectoryServices.ExtensionProperty','objectType':'ExtensionProperty','objectId':'93a26374-4135-4f29-9f24-4154522449ec','deletionTimestamp':null,'appDisplayName':'','name':'extension_33e037a7b1aa42ab96936c22d01ca338_CompInfo','dataType':'String','isSyncedFromOnPremises':false,'targetObjects':['User']},{'odata.type':'Microsoft.DirectoryServices.ExtensionProperty','objectType':'ExtensionProperty','objectId':'21a8a3d4-f4b4-45b4-8d07-55d450db35f2','deletionTimestamp':null,'appDisplayName':'','name':'extension_33e037a7b1aa42ab96936c22d01ca338_CompanyNameForSaasApp','dataType':'String','isSyncedFromOnPremises':false,'targetObjects':['User']},{'odata.type':'Microsoft.DirectoryServices.ExtensionProperty','objectType':'ExtensionProperty','objectId':'7b3109e0-8710-4d1a-81c3-2b6a83fb62ee','deletionTimestamp':null,'appDisplayName':'','name':'extension_33e037a7b1aa42ab96936c22d01ca338_Compania','dataType':'String','isSyncedFromOnPremises':false,'targetObjects':['User']}]}";
var o = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine(o.Value[0].Name);
}
output :
extension_33e037a7b1aa42ab96936c22d01ca338_Modulos
You can use DataContractSerializer
var serializer = new DataContractJsonSerializer(typeof(RootObject));
var ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
var root = serializer.ReadObject(ms) as RootObject;
But also you should mark your classes with [DataContract] attribute and members with [DataMember] attribute.
Like this:
[DataContract]
public class RootObject
{
[DataMember(Name = "odata.metadata")]
public string metadata { get; set; }
[DataMember]
public List<ActiveDirectorySchemaExtension> value { get; set; }
}
Also, you've lost one field in your class ActiveDirectorySchemaExtension - odataType. You can deserialize it like this:
[DataMember(Name = "odata.type")]
public string odataType { get; set; }

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.

JSON C# DeserializeObject Error with Newtonsoft.Json

I have a JSON string that I am getting from the BaseCamp API. I know for a fact that the JSON is valid, however, I am not able to DeserializeObject using Newtonsoft.Json.
I get an error saying:
Cannot deserialize the current JSON array (e.g.[1,2,3]) into type BaseCamp.Code.Projects+RootObject because the type requires a JSON objet (e.g. {"name":"value"}) to deserialize correctly.
The JSON (Unformated What is returned from the API Minus the URL's Values)
[
{
"id":6656986,
"name":"Physics Revamp",
"description":"ISU department of physics website redesign",
"archived":false,
"is_client_project":true,
"created_at":"2014-08-07T10:59:29.000-05:00",
"updated_at":"2014-10-30T09:18:01.000-05:00",
"trashed":false,
"color":"2c5322",
"draft":false,
"template":false,
"last_event_at":"2014-10-30T09:18:01.000-05:00",
"starred":false,
"url":"xxxxxxxxxxxxxxxxxxxxxxx",
"app_url":"xxxxxxxxxxxxxxx"
},
{
"id":7178664,
"name":"Physics Videos",
"description":"",
"archived":false,
"is_client_project":false,
"created_at":"2014-10-02T08:34:46.000-05:00",
"updated_at":"2014-10-23T08:40:17.000-05:00",
"trashed":false,
"color":"660099",
"draft":false,
"template":false,
"last_event_at":"2014-10-23T08:40:17.000-05:00",
"starred":false,
"url":"xxxxxxxxxxxxxxxxxxxxxxx",
"app_url":"xxxxxxxxxxxxxxxxxxx"
},
{
"id":6685451,
"name":"WZND Website 2014",
"description":"",
"archived":false,
"is_client_project":true,
"created_at":"2014-08-11T13:25:51.000-05:00",
"updated_at":"2014-10-30T11:26:39.000-05:00",
"trashed":false,
"color":"3185c5",
"draft":false,
"template":false,
"last_event_at":"2014-10-30T11:26:39.000-05:00",
"starred":false,
"url":"xxxxxxxxxxxxxxxxxx",
"app_url":"xxxxxxxxxxxxxxxxx"
}
]
My C# class:
public class Projects
{
public class RootObject
{
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
public bool archived { get; set; }
public bool is_client_project { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public bool trashed { get; set; }
public string color { get; set; }
public bool draft { get; set; }
public bool template { get; set; }
public string last_event_at { get; set; }
public bool starred { get; set; }
public string url { get; set; }
public string app_url { get; set; }
}
}
I am assuming something is wrong with the way my class is set up, but I can't see it.
You need to convert to an array of RootObject:
var json = JsonConvert.DeserializeObject<Projects.RootObject[]>(response);
or list (or any other collection you want for that matter)...
var json = JsonConvert.DeserializeObject<List<Projects.RootObject>>(response);

Categories

Resources