JSOn object not deserializing properly in wcf webservice side - c#

I am working on iOS project and sending the Json string to backend through wcf webservice, Its working successfully for many users but for some users backend getting incomplete json string.
Code for generating Json string
NSData *data = [NSJSONSerialization dataWithJSONObject:EmployeeDetails options:0 error:nil];
NSString *JsonString = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
And Attaching the json string with request by below code
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
EmployeeDetails is NSMutableDictionary with employee details.
And
Here is successful Json string deserialized from BackEnd
{"FirstName":"Donald","LastCBPaymentType":6,"AcceptEmail":true,"CellPhone":"321-300-6874","Position":"3","CarrierNum":"4","EmpNum":"96874"}
And Incomplete Json string
{"FirstName":"roset","LastCBPaymentType":6,"AcceptEmail":true,"CellPhone":"321-300-6874","Position":"3","CarrierNum":"4","EmpNum":"98799
The incomplete json string occuring in backend for some user.
Any one can help to solve this issue ?

Well, I'd say TomSwift is on the right track... It's apparent that the broken JSON is simply missing "} from the end of the string. That does indeed look like something being sanitised by a regex...
You really should find the source of the problem; But for a quick and dirty fix while you figure it out, you could just run your own regex on the JSON you receive and if it doesn't end with a "}, just add it... First do something like: '/"[0-9]+$/' (to check if there is an open numeric string at the end, if there is, you close it by adding " ) then check if '/}$/' (if } is the last char, if it isn't: add it).
Remember, the above would only be a temporary fix (as it is somewhat heavy and not really that pretty), but I could imagine myself being forced to do something like this, simply because of time constraints. If the issue is actually coming from within the API, you could tell the creators about it and use something like that fix above while they fixed it.
PS. If anyone does choose to use a fix like the above, please please please, for the love of all that you hold holy, leave a comment in the code explaining why you did it (as opposed to telling us what you did...).

I had a similar problem in PHP/CodeIgniter recently and the problem was that the JSON was being "sanitized" via some overly ambitious regular expressions before it arrived to my handler. Perhaps there's some similar sanitization that happens in WCF?
Things I would try:
Using Charles Proxy to confirm that the request (POST?) is actually sending the full body as you expect.
Try Content-Type application/json instead.

Related

SignalR encoding in JSON

I have a Windows service that publishes data to a .NET client and a web client over SignalR. I've recently had some funny issues, but can't quite get a consistent behavior.
The problem lies in serializing the degrees sign, i.e. "°C". Most of the time it is serialized correctly, but I've had a few times where I see the following in my debugger:
See how the first time the "°" is serialized correctly, but the second time we see the question marks in the diamonds?
I've read this means it is an invalid UTF-8 character. But then why do all the other properties serialize correctly? This is a screenshot where you see one correct and one incorrect, but the entire JSON contains hundreds of these "°C" strings that look correct.
So why this one exception? It's not always the same position/property, and it doesn't always happen. This makes me think it must be a combination with preceding/succeeding characters, no?
Any ideas how to fix this or at least how to investigate this further?
Update
This is how I do serialization. I set it up on startup:
var serializerSettings = new JsonSerializerSettings();
serializerSettings.Converters.Add(new StructuredAmountJsonConverter());
var serializer = JsonSerializer.Create(serializerSettings);
GlobalHost.DependencyResolver = new AutofacDependencyResolver(_lifetimeScope);
GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);
What's happening here is I'm telling SignalR to use Autofac to resolve dependencies. Then I register my JSON.NET serializer. The JSON.NET serializer has one custom converter, which converts my Amount class to the structure you see above (with a value and a unit property).
So you could think the problem lies in the converter, but then why is it working 95% of the time? Or should I specify the encoding in my converter?
Update 2
I've been using Fiddler to capture my network traffic and I can't see the wrong characters there. So I'm guessing the encoding problem is at the client side. I will investigate further.
Update 3
I've managed to capture the traffic in Fiddler and while it looks good in the Text view, when I select the HexView I do see something weird:
Notice how it says "°C" instead of "°C". So maybe it is sending it from the server in the wrong way?
Also, keep in mind my client is a .NET (WPF) client. This is my code to connect on the client side (simplified):
var url = "myUrl...";
_hubConnection = new HubConnection(url);
var hubProxy = _hubConnection.CreateHubProxy("MyHub");
hubProxy.On<object>("receive", OnDataReceived);
await _hubConnection.Start();
And when receiving data:
var message = JsonConvert.DeserializeObject<MyDataContract>(obj.ToString(), new StructuredAmountJsonConverter());
Update 4
This post makes me think this is happening:
The server/SignalR is sending my data as UTF-8, but the client is expecting latin-1 or Windows-1252 (probably the latter). So now I need to find out how I can make it use UTF-8.
May I know how you are serializing the objects? I think there is a way to specify the encoding types for serializing special characters like this. Here is a link I found- Special characters in object making JSON invalid (DataContractJsonSerializer)

C# deserialization from Java(android) header

I am working on some android project, so i need to send hashtags to the server by Header info.
So this is the server code they have for getting the hashtags.
if (Request.Headers.Contains("hashtags"))
newPost.HashTags = new System.Web.Script.Serialization.JavaScriptSerializer()
.Deserialize<List<string>> (Request.Headers.GetValues("hashtags").First());
and i really don't know how to send ArrayList in java side to a single parametar by Headers parametar.
conn.setRequestProperty("hashtags", "");
I guess i need to serialize somehow the list and send it as string?
Please if anyone knows anything share with me, i really appreciate it!
I found a solution
You need to post in this format
["element1","element2","element3"]
in simple String format.
Hope this helps!

Unexpected json result while calling the surveymonkey api

When calling the surveymonkey api I'm using
{\"survey_id\":\"47625442\"," +"\"fields[]\":\"['url']\"}"
as the json data the server needs to complete my request. while it is returning the data it is required it is not returning the additional URL i believe i am requesting. Does anyone know why this wouldn't give me this back?
EDIT https://developer.surveymonkey.com/mashery/get_collector_list this is the call im trying to make if this helps
As was pointed out in the comments: Your JSON formatting is off, so the API doesn't understand that you're asking for the URL.
For an understanding of what's going on, take a look at the example request in the link you provided; note the format of the fields section.
Try again, this time with:
{"survey_id": "47625442", "fields": ["url"]}
...which with the escapes will look like this....
{\"survey_id\": \"47625442\", \"fields\":[ \"url\" ]}"

No Json payload returned with api request [duplicate]

When calling the surveymonkey api I'm using
{\"survey_id\":\"47625442\"," +"\"fields[]\":\"['url']\"}"
as the json data the server needs to complete my request. while it is returning the data it is required it is not returning the additional URL i believe i am requesting. Does anyone know why this wouldn't give me this back?
EDIT https://developer.surveymonkey.com/mashery/get_collector_list this is the call im trying to make if this helps
As was pointed out in the comments: Your JSON formatting is off, so the API doesn't understand that you're asking for the URL.
For an understanding of what's going on, take a look at the example request in the link you provided; note the format of the fields section.
Try again, this time with:
{"survey_id": "47625442", "fields": ["url"]}
...which with the escapes will look like this....
{\"survey_id\": \"47625442\", \"fields\":[ \"url\" ]}"

Json Converter not recognising null attributes and throwing exceptions

Say I have a sample Json format string as
string per1 = #"[{""Email"":""AAA"",""mj_campaign_id"":""22"",""mj_contact_id"":""PPP"",""customcampaign"":""AAA"",""blocked"":""22"",""hard_bounce"":""PPP"",""blocked"":""22"",""hard_bounce"":""PPP""},"
+ #"{""Email"":""BBB"",""mj_campaign_id"":""25"",""mj_contact_id"":""QQQ"",""customcampaign"":""AAA"",""blocked"":""22"",""hard_bounce"":""PPP"",""blocked"":""22""},"
+ #"{""Email"":""CCC"",""mj_campaign_id"":""38"",""mj_contact_id"":""RRR"",""customcampaign"":""AAA"",""blocked"":""22"",""hard_bounce"":""PPP""}]";
I am trying to deserialize it using
var result = JsonConvert.DeserializeObject(per1);
Its working fine as long as all the rows of the string has values for the following attributes Email, mj_campaign_id, mj_contact_id, customcampaign, blocked, hard_bounce, error_related_to, error. But when I skip some sttribute values in some rows its throwing an error saying
Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.
Any help would be appreciated. Thanks
Your error is because you are not assigning a value to an object, which you need to do. If you remove the value, at least add an empty string.
THAT SAID!
Herein lies the danger of manually building JSON strings. You should always avoid it if you can. If you are reading from a web page, that web page should serialize the payload for you, and then you should deserialize it with whatever you are using to pull in the payload (controller, restful service, etc). The beauty of .NET is that it handles all of this plumbing for you and you really are going to run into painful issues if you try to reinvent the .NET wheel

Categories

Resources