JsonConvert.DeserializeObject weird issue - windows-phone-8

I am facing some weird problem. Here is my response handler class
public class AdvisoryResponse
{
public string category { get; set; }
public string text { get; set; }
public string link { get; set; }
public string created_on { get; set; }
public int profile_id { get; set; }
public int id { get; set; }
}
Here is code that de-serialize json string to object
string jsonStr = await response.Content.ReadAsStringAsync();
AdvisoryResponse res = JsonConvert.DeserializeObject<AdvisoryResponse>(jsonStr);
Now here is jsonStr value for first time :
{"category": "Crop", "text": "This is some msg", "created_on":
"07-08-2014 00:00:00", "id": 198513, "profile_id": 2947}
After de-serializing above string, I receive AdvisoryResponse object with profile_id = 2947
Here is jsonStr value at second time
{"category": "Crop", "text": "This is some msg", "created_on":
"07-08-2014 00:00:00", "id": 198513, "profile_id": 2949}
After de-serializing above string, I receive the AdvisoryResponse object with profile_id = 2947 & not 2949.
Please help me to understand whats happening here
Thanks
Aniruddha

Related

.Net 6 API not returning nested list objects

We are moving our APIs from .net 4.8 library to .Net 6. I cam across a weird problem where none of the nested objects (Costs) are being serialized.
I have tried adding the using in the startup but my apis dont work with this option on. I cant even see the controllers being hit with this options on.
Newtonsoft.Json.Serialization;
...............
services.AddControllers().AddNewtonsoftJson();
OR
`services.AddControllers().AddNewtonsoftJson(options =>`
`{`
`options.SerializerSettings.ContractResolver = new DefaultContractResolver();`
`options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;`
`});`
services.AddControllers().AddJsonOptions(o =>
{
o.JsonSerializerOptions.MaxDepth = 4;
o.JsonSerializerOptions.PropertyNamingPolicy = null;
o.JsonSerializerOptions.DictionaryKeyPolicy = null;
});
What Am I missing?
I expect the format below
`{
"Status": 200,
"Message": "Processed Successfully",
"Description": null,
"Errors": null,
"ResponseObject": {
"Costs": [
{
"Component": "xxx",
"Key1": "123",
"Key2": null,
"Key3": null,
"ProductCode": "x",
"From": "2021-08-05T00:00:00",
"To": "2021-08-05T23:59:59",
"Value": "1584",
"CurrencyCode": null,
"UnitOfMeasure": null
},
{
"Component": "X",
"Key1": "123",
"Key2": null,
"Key3": null,
"ProductCode": "Y",
"From": "2021-08-05T00:00:00",
"To": "2021-08-05T23:59:59",
"Value": "3131",
"CurrencyCode": null,
"UnitOfMeasure": null
}
]
}`
The C# object is as below:
public class Response
{
public int Status { get; set; }
public string Message { get; set; }
public string Description { get; set; }
public object Errors { get; set; }
public object ResponseObject { get; set; }
}
Below is the code used to populate the object:
var costsVM = new CostsVM();
var response = new Response();
costsVM.Costs.AddRange(costs);
response.ResponseObject = costsVM;
response.Status = 200;
response.Message = "Processed Successfully";
response.Description = null;
return Ok(response);
Cost VM is defined as below:
public class CostsVM
{
public List<CostsDTO> Costs = new List<CostsDTO>();
}
public class CostsDTO
{
public string Component { get; set; }
public string? Key1 { get; set; }
public string? Key2 { get; set; }
public string? Key3 { get; set; }
public string ProductCode { get; set; }
public DateTime From { get; set; }
public DateTime To { get; set; }
public string Value { get; set; }
public string? CurrencyCode { get; set; }
public string? UnitOfMeasure { get; set; }
}
I seem to have found the fix for it.
I needed to enable IncludeFields in JsonSerializer
services.AddMvc().AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = null;
options.JsonSerializerOptions.MaxDepth = 64;
options.JsonSerializerOptions.IncludeFields = true;
});

Xamarin Refit - Newtonsoft.Json.JsonSerializationException

I have some problems with JSON Serialization.
When I try to deserialize my JSON Object, it returns me this error :
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Project.Models.BookModel' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
My problem here is that I have to deserialize my object in two different ways : In a JSON array(e.g.[1,2,3]) to extract "_id", "user" and "name", and then in a JSON array(e.g.["name":"value"]) to extract "books". And I don't know how to do it. Or more precisely, I don't know if it's posible with Refit.
Here is my JSON :
[
{
"_id": "5c014a1e43b6804ed7b642b2",
"__v": 0,
"user": "5c014a1d43b6804ed7b642b1",
"name": "Favoris",
"books": [
{
"_id": "5a8f12e16a16fa06d1f5b0cb",
"title": "Harry Potter et la Chambre des Secrets",
"author": {
"_id": "5a8f12e16a16fa06d1f5b0bd",
"name": "J K Rowling",
"__v": 0
},
"literaryGenre": "Juvenile Fiction",
"isbn": 9781781101049,
"externalImage": "...",
"__v": 0,
"content": {
"brief": "test1"
}
},
{
"_id": "5a8f12e16a16fa06d1f5b0d0",
"title": "Harry Potter et la Coupe de Feu",
"author": {
"_id": "5a8f12e16a16fa06d1f5b0bd",
"name": "J K Rowling",
"__v": 0
},
"literaryGenre": "Juvenile Fiction",
"isbn": 9781781101063,
"externalImage": "...",
"__v": 0,
"content": {
"brief": "test2"
}
}
]
}
]
Here is my code :
public async void ViewLibrary()
{
IProjectApi response = ProjectRepository.Instance.ProjectApi;
List<LibraryModel> library = await response.GetLibrary("5c014a1d43b6804ed7b642b1");
this.LibraryItems = library;
}
And my object LibraryModel :
public class LibraryModel
{
public string _id { get; set; }
public string user { get; set; }
public string name { get; set; }
public BookModel books { get; set; }
}
And my method GetLibrary :
[Get("/api/library/user/{UserId}")]
Task<List<LibraryModel>> GetLibrary(string UserId);
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
'Project.Models.BookModel' because the type requires a JSON object
(e.g. {"name":"value"})
In json result your BookModel returning multiple records, so it should be defined as List<BookModel>.
In LibraryModel try using public List<BookModel> books { get; set; }.
Implement these classes anywhere in your code and try to deserialize your json with these classes.
public class Author
{
public string _id { get; set; }
public string name { get; set; }
public int __v { get; set; }
}
public class Content
{
public string brief { get; set; }
}
public class Book
{
public string _id { get; set; }
public string title { get; set; }
public Author author { get; set; }
public string literaryGenre { get; set; }
public object isbn { get; set; }
public string externalImage { get; set; }
public int __v { get; set; }
public Content content { get; set; }
}
public class RootObject
{
public string _id { get; set; }
public int __v { get; set; }
public string user { get; set; }
public string name { get; set; }
public List<Book> books { get; set; }
}

Newtonsoft json and graph api

i use Newtonsoft json to Deserialize facebook graph api response.
for example when i parse user posts that the response is like:
data": [
{
"story": "",
"created_time": "",
"id": ""
}]
i have created a class like:
public class FacebookPost
{
public string created_time { get; set; }
public string id { get; set; }
public string story { get; set; }
}
and the Newtonsoft appends the values directly in the class and i can use them.
my problem is when i am trying to parse comments when the api response is like:
"data": [
{
"created_time": "",
"from": {
"name": "",
"id": ""
},
"message": "",
"id": ""
}]
there for example the name and id is inside the from section,
how do i have to structure the classes in order to can take values for from.name and from.id?
thank you very much
---------------------------- new add ------
i use the following classes :
public class FacebookCommentsResults
{
public PostComments[] data { get; set; }
public FacebookPagingInfo Paging { get; set; }
}
public class PostComments
{
public string created_time { get; set; }
public From from { get; set; }
}
public class From
{
public string name { get; set; }
public string id { get; set; }
}
the line var created_time = comment.created_time; WORKS FINE!
the next line var name = comment.name; GIVES ERROR --> Reactions.PostComments' does not contain a definition for 'name' and no extension method 'name' accepting a first argument of type 'Reactions.PostComments' could be found (are you missing a using directive or an assembly reference?)
when the response is
"data": [
{
"created_time": "",
"from": {
"name": "",
"id": ""
},
"message": "",
"id": ""
}]
Now the json schema is changed, so we have to change our Classes. Reason is from is an another object in our main json, so we need the below classes to access from.id and from.name
public class From
{
public string name { get; set; }
public string id { get; set; }
}
public class FacebookPost
{
public string created_time { get; set; }
public From from { get; set; }
public string message { get; set; }
public string id { get; set; }
}
Edit
the line var created_time = comment.created_time; WORKS FINE! the next
line var name = comment.name; GIVES ERROR --> Reactions.PostComments'
does not contain a definition for 'name' and no extension method
'name' accepting a first argument of type 'Reactions.PostComments'
could be found (are you missing a using directive or an assembly
reference?)
from is an object and in that object name is an attribute, so you cannot access it by giving comment.name. First you need to take the from object from comment and then you can retrieve the name attribute.

How to parse the Json data in WP8?

I'm newbie to windows phone 8 development. I am working on application in which I need parse the Json. please help me with this json data
{
"School": [
{
"info": {
"name": "Dary",
"description": "Student",
"startAt": "",
"endAt": "",
"status": "approved",
"type": 7
},
"gui": {
"size": 60,
"sizeMB": "1.7 M"
}
},
{
"info": {
"name": "Henry",
"description": "Student",
"startAt": "",
"endAt": "",
"status": "approved",
"type": 7
},
"gui": {
"size": 60,
"sizeMB": "1.7 M"
}
}
]
}
this is class
public class Info
{
public string name { get; set; }
public string description { get; set; }
public string startAt { get; set; }
public string endAt { get; set; }
public string status { get; set; }
public int type { get; set; }
}
public class Gui
{
public int size { get; set; }
public string sizeMB { get; set; }
}
public class School
{
public Info info { get; set; }
public Gui gui { get; set; }
}
public class RootObject
{
public List<School> School { get; set; }
}
Thanks in advance.
As Peter Torr suggests, JSON.NET is a great option. There is a DataContractJsonSerializer for serialization in the .net framework, but its not very robust. You can easily add JSON.NET to your project with Nuget. Place your json in a string variable
string json = "<<your json string>>"
or read from a file
string json = File.ReadAllText("<<path to file>>");
Then, the following code will deserialize your text.
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
You can lose the root object (it looks like it came from a javascript to C# converter) if you keep only the json array (the text between the brackets [] ), and then you can deserialize just the array.
List<School> school = JsonConvert.DeserializeObject<List<School>>(json);

Trouble deserializing Json from REST service

I'm having the hardest time deserializing a json string.
I was using the RestSharp api which worked great if I specified the RootElement on the request. I then moved to Hammock for the OAuth functionality, but the deserialization isn't working so easily.
I've tried using DataContractJsonSerializer
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List));
var member = (List)ser.ReadObject(response.ContentStream);
but this gives me an InvalidCastException.
I tried JsonConvert
var members = JsonConvert.DeserializeObject<List<Member>>(response.Content);
but I get the exception: Cannot deserialize JSON object into type 'System.Collections.Generic.List`1[Member]'.
RestSharp took care of this easily when calling ExecuteAsync. Client.ExecuteAsync<List<Member>>(request, (response) =>
I'm at my wits end. Maybe I need a Hammock equivalent to RestSharp's RootElement property?? Is it just that my Json is difficult to convert?
Here is my Member object
public partial class Member
{
public string State { get; set; }
public string Joined { get; set; }
public string lat { get; set; }
public string Zip { get; set; }
public string Bio { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Id { get; set; }
public string Link { get; set; }
public string Country { get; set; }
public string Visited { get; set; }
public string Photo_url { get; set; }
public string lon { get; set; }
}
here is the Json:
{
"results": [
{
"zip": "11111",
"lon": "-122.22000122070312",
"photo_url": "http: //photos1.aaaaa.com/photos/member/1/6/c/e/member_4469838.jpeg",
"link": "http: //www.aaaa.com/members/7804365",
"state": "AA",
"lang": "en_US",
"city": "MyCity",
"country": "us",
"id": "7804365",
"visited": "Sat Feb 19 02: 36: 40 EST 2011",
"topics": [
{
"id": 3340,
"urlkey": "pickupsoccer",
"name": "Pick-up Soccer"
},
{
"id": 468,
"urlkey": "dads",
"name": "Dads"
},
{
"id": 20557,
"urlkey": "coed-soccer",
"name": "Coed Soccer"
},
{
"id": 148421,
"urlkey": "windowsphone",
"name": "Windows Phone"
}
],
"joined": "Thu Aug 07 15: 32: 06 EDT 2008",
"bio": "",
"name": "aaa bbbb",
"other_services": {
"linkedin": {
"identifier": "http: //www.bbb.com/in/zzzzz"
}
},
"lat": "47.790000915527344"
}
],
"meta": {
"lon": "",
"count": 1,
"link": "https: //api.aaaaa.com/members",
"next": "",
"total_count": 1,
"url": "https: //api.aaaaa.com/members?relation=self&order=name&offset=0&format=json&page=800",
"id": "",
"title": "Members",
"updated": "Fri Sep 10 13: 08: 07 EDT 2010",
"description": "API method",
"method": "Members",
"lat": ""
}
}
UPDATE
Adding a wrapper object for my Member class that encapsulates the entire json result fixed this.
public partial class Members
{
public List<Member> results { get; set; }
public object meta { get; set; }
}
Then I can can deserialize using the following:
var members = JsonConvert.DeserializeObject<Members>(jsonstring);
There are about three problem areas in your JSON data:
The way it is presented here, it contains a lot of backslashes and double quotes at the beginnging and end that don't work in JSON. It's difficult to tell from your question whether this is an artifact of copying it from the VisualStudio debugger or is really a problem in the data.
The transmitted data is not a list of Member instance but rather an object containing both a list of member instances and some additional meta information. So you need to introduce an additional class with a the two members results and meta.
Your class Member uses properties starting with an uppercase letter while the JSON data uses all lowercase letters. You can either change the property names or uses data DataMember annoation:
So the solution could be:
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(JsonResponse));
JsonResponse jsonResponse = (JsonResponse)ser.ReadObject(response.ContentStream);
with the following class definitions:
[DataContract]
public partial class Member
{
[DataMember(Name = "state")]
public string State { get; set; }
[DataMember(Name = "joined")]
public string Joined { get; set; }
[DataMember(Name = "lat")]
public string Lat { get; set; }
[DataMember(Name = "zip")]
public string Zip { get; set; }
[DataMember(Name = "bio")]
public string Bio { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "state")]
public string City { get; set; }
[DataMember(Name = "city")]
public string Id { get; set; }
[DataMember(Name = "link")]
public string Link { get; set; }
[DataMember(Name = "country")]
public string Country { get; set; }
[DataMember(Name = "visited")]
public string Visited { get; set; }
[DataMember(Name = "photo_url")]
public string PhotoUrl { get; set; }
[DataMember(Name = "lon")]
public string Lon { get; set; }
}
[DataContract]
public class Meta
{
[DataMember(Name = "lon")]
public string Lon { get; set; }
[DataMember(Name = "count")]
public int Count { get; set; }
[DataMember(Name = "link")]
public string Link { get; set; }
[DataMember(Name = "next")]
public string Next { get; set; }
[DataMember(Name = "total_count")]
public int TotalCount { get; set; }
}
[DataContract]
public class JsonResponse
{
[DataMember(Name = "results")]
public List<Member> Results { get; set; }
[DataMember(Name = "meta")]
public Meta Meta { get; set; }
}
In our project we r using Hammok for this, you can try to modify your class like this:
[DataContract]
public partial class Member
{
[DataMember(Name="zip")]
public string Zip { get; set; }
[DataMember(Name="photo_url")]
public string Photo_url { get; set; }
//Etc.
}
try using Json.net.
i found DataContractJsonSerializer too fetureless.
json.net provides great functionality.
it can be found at this link
http://json.codeplex.com/
it contains the .dll files and documentatio as well.
for web Documentation
http://james.newtonking.com/projects/json/help/