Bad JSON escape sequence - json.net

I have this JSON string:
{"Time":"11/03/2015 05:32:29.273","Message":"Error loading chirps. Cannot create file \U+0022E:\U+005CUsers\U+005Cgwardell\U+005CDocuments\U+005CSRChirp\U+005CPictures\U+0022. Access is denied","Source":"BT","Method":"GetChirpsFromServer.SaveMedia.SaveBitmap","ChirpID":"9851","LogType":"Error","DeviceType":"Win","Action":"RecordLog","UserID":"98000001","DeviceID":"3675"}
as near as I can tell it conforms to the RFC 7159 JSON Standard.
This validator tells me it's OK:
http://freeformatter.com/json-validator.html
However, when I run it through this code:
public class TAction
{
public string Action = "";
}
...
TAction Params = JsonConvert.DeserializeObject<TAction>(JSON);
I get:
Newtonsoft.Json.JsonReaderException: Bad JSON escape sequence: \U. Path 'Message', line 1, position 88.
At position 88 is the first escaped quite mark: \U+0022
What is wrong?
Is this a bug in JsonConvert?

I started going with \u0022 and \" and \n and that was going good.
Then I got another idea and looked more closely at the class I was using on my mobile client and found that TJSONObject (Delphi Object Pascal) had another stringify method besides ToString which doesn't do any escaping. It turns out the ToJSON method does all of the required escaping and is compatible with JsonConvert (in my Asp.net web-service) so I didn't have to do any custom escaping at all.
Thanks for the pointers. They got me headed in the right direction.

Related

Parse Google JSON response in VB.NET

I'm trying to parse the JSON response form google. This is what I currently have:
Dim x As New System.Web.Script.Serialization.JavaScriptSerializer
Dim gJson As String = ""
Dim wClient As New WebClient
wClient.Proxy = System.Net.HttpWebRequest.DefaultWebProxy
gJson = wClient.DownloadString("https://www.googleapis.com/...alt=json")
Dim results As gResponseClass = x.Deserialize(Of gResponseClass)(gJson)
gResponseClass as follows here: PasteBin
I keep getting the following exception thrown:
Invalid object passed in, member name expected. (6678): .... *the json response here* ...
Is there any blatant problems or solutions I could implement?
EDIT :
The JSON response from google: JSON Response
EDIT
Just for continuation purposes: the erros is cased indeed by the "": inside the pagemap node on facebook pages. I have resorted to calling a cleanup function as follows:
json = json.Replace(""""":", """page_id"":")
Return json
If anyone has a better way, please let me know!
Thanks again.
It looks like this is the bit of the JSON it's having trouble with:
"": [
{
"page_id": "66721388277"
}
],
I'm not a JSON expert, but I can see why it might be surprised by that. As I mentioned, it can be parsed by Json.NET (at least as a JObject) so you might want to try using that instead.
Original answer, still relevant
The DeserializeObject method specifies:
This deserialization method does not try to cast the root of the object graph to a specific type, as with the Deserialize method.
So I'd be surprised if it managed to cast to gResponseClass anyway. Have you tried using the Deserialize method instead?
(I'd have expected a compile-time error to be honest - do you have option strict and option explicit on?)
That may well not be the problem you're facing, but it's the first thing I'd look at anyway :) The JSON parses fine with JSON.NET.

Backslashes in JSON string

I'm not familiar with this format:
{"d":"{\"Table\":[{\"pCol\":12345,\"fCol\":\"jeff\",\"lCol\":\"Smith\",\"dId\":1111111,\"tDate\":\"\\/Date(1153033200000-0700)\\/\"}]}"}
I'm using Newtonsoft to serialize my DataSet that I'm returning from my ASP.Net webservice. The above JSON string is what Firebug is returning. I have checked this JSON using jsLint and it is good.
In firebug I see the JSON data and my first alert('success'); However when I try to alert(msg.d.Table); I get nothing. Not an alert box or an error in Firebug... I think it has something to do with these backslashes... But I'm not sure.
Any ideas?
Those backslashes are escape characters. They are escaping the double quotes inside of the string associated with d. The reason you cant alert msg.d.Table is because the value of d is a string. You have to use JSON.parse to parse that JSON string into a JSON object.
Then, you have to convert Table back to a string to alert it.
Something like this:
var dObj = JSON.parse(msg.d);
alert(JSON.stringify(dObj.Table, null, 2));
The ASP.Net webservice is already serializing the return value to JSON. (in a d property for security reasons)
When you return pre-serialized JSON data, it thinks you're giving it a normal string, and proceeds to serialize the string as JSON.
Therefore, you get a JSON object with a d property that contains the raw JSON string (with correctly escaped quotes) that you returned.
You should return the raw object and let ASP.Net serialize it for you instead of serializing it yourself.

parsing simple xml with jquery from asp.net webservice

I'm breaking my head over this for a while now and I have no clue what I do wrong.
The scenario is as followed, I'm using swfupload to upload files with a progressbar
via a webservice. the webservice needs to return the name of the generated thumbnail.
This all goes well and though i prefer to get the returned data in json (might change it later in the swfupload js files) the default xml data is fine too.
So when an upload completes the webservice returns the following xml as expected (note I removed the namespace in webservice):
<?xml version="1.0" encoding="utf-8"?>
<string>myfile.jpg</string>
Now I want to parse this result with jquery and thought the following would do it:
var xml = response;
alert($(xml).find("string").text());
But I cannot get the string value. I've tried lots of combinations (.html(), .innerhtml(), response.find("string").text() but nothing seems to work. This is my first time trying to parse xml via jquery so maybe I'm doing something fundemantally wrong. The 'response' is populated with the xml.
I hope someone can help me with this.
Thanks for your time.
Kind regards,
Mark
I think $(xml) is looking for a dom object with a selector that matches the string value of XML, so I guess it's coming back null or empty?
The First Plugin mentioned below xmldom looks pretty good, but if your returned XML really is as simply as your example above, a bit of string parsing might be quicker, something like:
var start = xml.indexOf('<string>') + 8;
var end = xml.indexOf('</string>');
var resultstring = xml.substring(start, end);
From this answer to this question: How to query an XML string via DOM in jQuery
Quote:
There are a 2 ways to approach this.
Convert the XML string to DOM, parse it using this plugin or follow this tutorial
Convert the XML to JSON using this plugin.
jQuery cannot parse XML. If you pass a string full of XML content into the $ function it will typically try to parse it as HTML instead using standard innerHTML. If you really need to parse a string full of XML you will need browser-specific and not-globally-supported methods like new DOMParser and the XMLDOM ActiveXObject, or a plugin that wraps them.
But you almost never need to do this, since an XMLHttpRequest should return a fully-parsed XML DOM in the responseXML property. If your web service is correctly setting a Content-Type response header to tell the browser that what's coming back is XML, then the data argument to your callback function should be an XML Document object and not a string. In that case you should be able to use your example with find() and text() without problems.
If the server-side does not return an XML Content-Type header and you're unable to fix that, you can pass the option type: 'xml' in the ajax settings as an override.

how to handle special characters in strings in a web service?

To show this fundamental issue in .NET and the reason for this question, I have written a simple test web service with one method (EditString), and a consumer console app that calls it.
They are both standard web service/console applications created via File/New Project, etc., so I won't list the whole code - just the methods in question:
Web method:
[WebMethod]
public string EditString(string s, bool useSpecial)
{
return s + (useSpecial ? ((char)19).ToString() : "");
}
[You can see it simply returns the string s if useSpecial is false. If useSpecial is true, it returns s + char 19.]
Console app:
TestService.Service1 service = new SCTestConsumer.TestService.Service1();
string response1 = service.EditString("hello", false);
Console.WriteLine(response1);
string response2 = service.EditString("hello", true); // fails!
Console.WriteLine(response2);
[The second response fails, because the method returns hello + a special character (ascii code 19 for argument's sake).]
The error is:
There is an error in XML document (1, 287)
Inner exception: "'', hexadecimal value 0x13, is an invalid character. Line 1, position 287."
A few points worth mentioning:
The web method itself WORKS FINE when browsing directly to the ASMX file (e.g. http://localhost:2065/service1.asmx), and running the method through this (with the same parameters as in the console application) - i.e. displays XML with the string hello + char 19.
Checking the serialized XML in other ways shows the special character is being encoded properly (the SERVER SIDE seems to be ok which is GOOD)
So it seems the CLIENT SIDE has the issue - i.e. the .NET generated proxy class code doesn't handle special characters
This is part of a bigger project where objects are passed in and out of the web methods - that contain string attributes - these are what need to work properly. i.e. we're de/serializing classes.
Any suggestions for a workaround and how to implement it?
Or have I completely missed something really obvious!!?
PS. I've not had much luck with getting it to use CDATA tags (does .NET support these out of the box?).
You will need to use byte[] instead of strings.
I am thinking of some options that may help you. You can take the route using html entities instead of char(19). or as you said you may want to use CDATA.
To come up with a clean solution, you may not want to put the whole thing in CDATA. I am not sure why you think it may not be supported in .NET. Are you saying this in the context of serialization?

How to stop .NET from encoding an XML string with XML.Serialization

I am working with some Xml Serialization in ASP.NET 2.0 in a web service. The issue is that I have an element which is defined such as this:
<System.Xml.Serialization.XmlElementAttribute(Form:=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable:=True)> _
Public Property COMMENTFIELD() As String
Get
Return CommentField ' This is a string
End Get
Set(ByVal value as String)
CommentField = value
End Set
End Property
Elsewhere in code I am constructing a comment and appending
as a line-break (according to the rules of the web service we are submitting to) between each 'comment', like this: (Please keep in mind that
is a valid XML entity representing character 10 (Line Feed I believe).
XmlObject.COMMENTFIELD = sComment1 & "
" & sComment2
The issue is that .NET tries to do us a favor and encode the & in the comment string which ends up sending the destination web service this: &#xA;, which obviously isn't what we want.
Here is what currently happens:
XmlObject.COMMENTFIELD = sComment1 & "
" & sComment2
Output:
<COMMENTFIELD>comment1 &#xA comment2</COMMENTFIELD>
Output I NEED:
<COMMENTFIELD>comment1
comment2</COMMENTFIELD>
The Question Is: How do I force the .NET runtime to not try and do me any favors in regards to encoding data that I already know is XML compliant and escaped already (btw sComment1 and sComment2 would already be escaped). I'm used to taking care of my XML, not depending on something magical that happens to escape all my data behind my back!
I need to be able to pass valid XML into the COMMENTFIELD property without .NET encoding the data I give it (as it is already XML). I need to know how to tell .NET that the data it is receiving is an XML String, not a normal string that needs escaped.
If you look at the XML spec section 2.4, you see that the & character in an element's text always used to indicate something escaped, so if you want to send an & character, it needs to be escaped, e.g., as & So .Net is converting the literal string you gave it into valid XML.
If you really want the web service to receive the literal text &, then .NET is doing the correct thing. When the web service processes the XML it will convert it back to the same literal string you supplied on your end.
On the other hand, if you want to send the remote web service a string with a newline, you should just construct the string with the newline:
XmlObject.COMMENTFIELD = sComment1 & "\n" & sComment2
.Net will do the correct thing to make sure this is passed correctly on the wire.
It is probably dangerous to mix two different encoding conventions within the same string. Since you have your own convention I recommend explicitly encoding the whole string when it is ready to send and explicitly decoding it on the receiving end.
Try the HttpServerUtility.HtmlEncode Method (System.Web) .
+tom

Resources