Json.Net JsonConvert not deserializing properly? - windows-phone-7

I'm using Json.Net to handle the deserialzing of the response of API calls from the Pipl.com API in my application, and it works fine but for some strange reason it won't deserialize a specific property of the JSON string that I feed to the JsonConvert.DeserializeObject method.
My class is this:
public class Source
{
public string Dsname { get; set; }
public bool IsSponsored { get; set; }
public string Url { get; set; }
public string Domain { get; set; }
public uint ExternalID { get; set; }
public Source()
{
}
}
and everything except the Dsname gets deserialized properly. The Json to be converted is like this:
"source": {
"#is_sponsored": false,
"#ds_name": "Personal Web Space -MySpace",
"url": "http://www.foo.bar"
"domain": "myspace.com"
}
Any idea how to go about this problem? Thank you in advance.

I added a wrapper class and specified the property name as attributes, like this:
public class Source
{
[JsonProperty(PropertyName = "#ds_name")]
public string Dsname { get; set; }
[JsonProperty(PropertyName = "#is_sponsored")]
public bool IsSponsored { get; set; }
public string Url { get; set; }
public string Domain { get; set; }
public uint ExternalID { get; set; }
}
public class RootObject
{
public Source source { get; set; }
}
Then I was able to deserialize fine:
var json = "{\"source\": { \"#is_sponsored\": true, \"#ds_name\": \"Personal Web Space -MySpace\", \"url\": \"http://www.foo.bar\", \"domain\": \"myspace.com\"}}";
var des = JsonConvert.DeserializeObject<RootObject>(json);
Note that I:
- wrapped your sample in a curly braces to make it valid JSON
- added a missing comma
- changed the value of "#is_sponsored" to not be the default value to verify it is desearialized correctly.

Ok I realize, this is a pretty old thread. But I ran into a similar issue earlier and came across this thread.
In my case the class I was trying to se/deserialize had a List<ClassName> public property in it. Which serialized fine, but wont deserialize. I switched it to ClassName[] and the fixed the deserialization problem.
Hope it helps someone else who comes across this thread, or at least gives them something else to look for.

Related

AJAX Posting Slickgrid data to MVC

I have a slickgrid and am attempting to save its data back to the server.
When I breakpoint on the server, I can see the data in the Request.Form object, but I can't make it work with my object.
My data looks like...
[
{"id":"0","LineNumber":"","Detail":"MOT cost","Code":" ","Qty":"1","Est":" ","CustomerDamage":false,"Cost":"44.00","Value":"44.00","VAT":true,"SelfBillingLine":"False","DefectStatus":" "},
{"id":"62","LineNumber":"","Detail":"CRACKS IN Chassis","Code":"TLMA02","Qty":"1","Est":"","CustomerDamage":false,"Cost":"35.00","Value":"35.00","VAT":true,"SelfBillingLine":"False","DefectStatus":"Large repair"},
{"id":"63","LineNumber":"","Detail":"TEAR IN N/S CURTAIN","Code":"TLMA02","Qty":"1","Est":"","CustomerDamage":true,"Cost":"10.00","Value":"10.00","VAT":true,"SelfBillingLine":"False","DefectStatus":"Customer"}
]
I am posting with a button onclick...
$("#SBSave").click(function() {
debugger;
var details = JSON.stringify(defectrows);
save('SBDetail/SaveSBItem', details);
});
I have tried a number of things to receive the data, none of them work.
My controller...
[HttpPost]
public void SaveSBItem(SelfBillDetailList details, string Approve = "")
{
// Actions here.
}
My model...
Trying a number of things, neither work...
public class SelfBillDetailList
{
public IEnumerable<SelfBillingIncomingDetail> IncomingDetails { get; set; }
}
public class SelfBillingIncomingDetail
{
public int id { get; set; }
public string Code { get; set; }
public string LineNumber { get; set; }
public string Detail { get; set; }
public string Action { get; set; }
public string Qty { get; set; }
public string Est { get; set; }
public bool VAT { get; set; }
public bool CustomerDamage { get; set; }
public string Cost { get; set; }
public string Value { get; set; }
public DateTime Received { get; set; }
public string DefectStatus { get; set; }
public bool SelfBillingLine { get; set; }
}
So, I have tried an individual SelfBillingIncomingDetail and also a the SelfBillDetailList.
Neither work.
I have even sent an individual row, again, neither work.
I want to send it as a group, so it will be an array of SelfBillingIncomingDetail but nothing works.
Thank you for your help.
I have done it again... eventually found an answer after looking for ages.
Darin Dimitrov's answer in
Post an Array of Objects via JSON to ASP.Net MVC3
let me to the answer.
It seems that when sending the data, I need to give the array of data the same name as the property name in SelfBillDetailList, so...
var details = JSON.stringify({IncomingDetails : defectrows});
fixes it.

OnDeserialized for JSON causing object to be null

I have a route on my WebAPI project that accepts an object as input ExportPostData. ExportPostData has a property called "contract" of type Contract which was successfully being populated when I called the route. I added the [OnDeserialized] tag to the Contract class and now it always fails deserialization. There are no errors thrown, just Contract is null. I have no idea how to debug this since my OnDeserialized method never even gets hit.
ExportPostData
public class ExportPostData
{
public Contract contract { get; set; }
public bool includeSubItems { get; set; }
public string user { get; set; }
public string[] projects { get; set; }
}
Contract
public class ZEstimateContract
{
public string _id { get; set; }
public string contractName { get; set; }
public string contractNumber { get; set; }
public string updatedBy { get; set; }
public DateTime updated_at { get; set; }
[OnDeserialized()]
internal void Deserialized()
{
// THIS NEVER GETS HIT
Console.WriteLine("I'm deserialized");
}
}
Change
[OnDeserialized()]
internal void Deserialized()
{
// THIS NEVER GETS HIT
Console.WriteLine("I'm deserialized");
}
to this:
[OnDeserialized]
internal void Deserialized(StreamingContext context)
{
// THIS GETS HIT NOW
Console.WriteLine("I'm deserialized");
}
Without the parameter, the method's signature doesn't match what OnDeserialized is looking for. See this article for details: http://msdn.microsoft.com/en-us/library/system.runtime.serialization.ondeserializedattribute.aspx

Parse.com - Adding <user>Pointer __User & ACL

I am attempting to add a row to a Class in my Parse database using the API
I have managed to get the row added but I noticed that both the 'ACL & user__user' fields are blank.
My Request class looks like this:
public class AccountDataRequest
{
public string OrderNo { get; set; }
public string SiteName { get; set; }
public string CreditDebit { get; set; }
public int Amount { get; set; }
public int CreditBalance { get; set; }
}
And my function looks like this:
public static AccountDataResponse AddTransaction(AccountDataRequest details)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.parse.com/1/classes/AccountData");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("X-Parse-Application-Id", "xxxxx");
httpWebRequest.Headers.Add("X-Parse-REST-API-Key", "xxxxx");
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = JsonConvert.SerializeObject(details);
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return JsonConvert.DeserializeObject<AccountDataResponse>(result);
}
}
}
The 'user__user' links to the 'objectID(String)' in mu Users class.
I have tried adding it to my class as a string but it throws and error.
Can anyone tell me how to get the ACL and 'user__user' populated please?
Thanks
UPDATE:
I have learnt that the Pointer is a structure so have amended my classes as follows:
public class AccountDataRequest
{
public string OrderNo { get; set; }
public string SiteName { get; set; }
public string CreditDebit { get; set; }
public double Amount { get; set; }
public int CreditBalance { get; set; }
public Pointer Pointer { get; set; }
}
public class Pointer
{
public string __type { get; set; }
public string className { get; set; }
public string objectId { get; set; }
}
So, when I now call the API with the following:
POST https://api.parse.com/1/classes/AccountData HTTP/1.1
Content-Type: application/json
X-Parse-Application-Id: xxxxx
X-Parse-REST-API-Key: xxxxx
Host: api.parse.com
Content-Length: 163
Expect: 100-continue
Connection: Keep-Alive
{"OrderNo":"9","SiteName":"Trev","CreditDebit":"Debit","Amount":1.0,"CreditBalance":999,"Pointer":{"__type":"Pointer","className":"AccountData","objectId":"fvJ8jPjyjx"}}
This call produces no errors and returns a createddate and an objectid but the user(Pointer <__User> is still null.
I also tried changing the className to "__User" to which the API responds:
{"code":111,"error":"invalid type for key Pointer, expected *AccountData, but got *_User"}
This is what the empty column looks like in my AccountData class
And I am trying to tie it to the objectId in my User table:
Can anyone see what is wrong please?
If the column in Parse is defined as a Pointer to _User, then you need to pass the appropriate structure to Parse and not just the objectId. Take a look at the Data Types section of the Parse REST SDK. It has a paragraph and sample for passing a Pointer structure through the API.
Similarly, for ACLs you need to specify that structure as well. Details for it are in the security docs for the SDK.
In both cases, if you want to use an object->JSON converter, you'll need to build an object that appropriately represents that structure. That'll be a bit easier for Pointers than ACLs as the former has predefined keys whereas the latter uses dynamic key names (e.g. objectIds and role names).
Updated to include class definition
public class AccountDataRequest
{
public string OrderNo { get; set; }
public string SiteName { get; set; }
public string CreditDebit { get; set; }
public double Amount { get; set; }
public int CreditBalance { get; set; }
public Pointer user { get; set; }
}

How to define xml attributes using web api and model binding

I'm creating an xml feed of products which needs to match the clients scheme exactly.
I'm using web api. I would like the property extractDate to be an attribute. The following code is outputting extractDate as an element not an attribute
public Feed GetProducts()
{
var feed = new Feed()
{
extractDate = "extractDate",
incremental = true,
name = "name",
Brands = GetBrands(),
Categories = GetCategories(),
Products = GetProducts()
};
return feed;
}
Here is my model Feed. Note the following doesn't seem to turn the element into an attribute
[XmlAttribute(AttributeName = "extractDate")]
public class Feed
{
[XmlAttribute(AttributeName = "extractDate")] //attribute is ignored
public string extractDate { get; set; }
public bool incremental { get; set; }
public string name { get; set; }
public List<Brand> Brands { get; set; }
public List<Category> Categories { get; set; }
public List<Product> Products { get; set; }
}
How do i output
<feed extractDate="2012/01/01"
// other logic
/>
Web API by default uses DataContractSerializer in XmlMediaTypeFormatter and probably that's the reason you are not seeing your attribute decorations taking effect. Do you have the XmlSerializer enabled on the XmlMediaTypeFormatter to see your expected output?
config.Formatters.XmlFormatter.UseXmlSerializer = true;
Also, you could set XmlSerializer only for specific types too using the following api:
config.Formatters.XmlFormatter.SetSerializer<>
Edit
Managed to simulate your issue with a blank project and Kiran's answer seems to do the trick.Just add this line in your controller(for testing purposes, it should probably be in your global.asax)
GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;
Do you have the [XmlRoot] on top of your class or is it missing?
Not sure the attribute will work without an xml class decorator.
A simple sanity check you could do is serialize the class without web api involved to make sure it's nothing silly but actually web api related.
How about this:
[XmlRoot("feed")]
public class Feed
{
[XmlAttribute(AttributeName = "extractDate")]
public string extractDate { get; set; }
public bool incremental { get; set; }
public string name { get; set; }
public List<Brand> Brands { get; set; }
public List<Category> Categories { get; set; }
public List<Product> Products { get; set; }
}

JSON Nullable Deserialization Error

Suppose you have a simple struct, like so:
public struct Point
{
public int X { get; set; }
public int Y { get; set; }
}
And a sample class like so:
public class Map
{
public int ID { get; set; }
public Point? PointA { get; set; }
///...
}
Now, suppose you are passing Map via AJAX as JSON. Question, what value should be passed for the not null scenario?
It may matter that JavaScriptSerializer is being used in a C# 3.5 ASP.NET ASMX web service.
The issue is what I listed in my comment about the question. The automatic properties were the issue. I converted the property and the issue was resolved.

Resources