Backslashes in JSON string - asp.net

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.

Related

Bad JSON escape sequence

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.

"<" character in JSON data is serialized to \u003c

I have a JSON object where the value of one element is a string. In this string there are the characters "<RPC>". I take this entire JSON object and in my ASP.NET server code, I perform the following to take the object named rpc_response and add it to the data in a POST response:
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
HttpContext.Current.Response.AddHeader("Pragma", "no-cache");
HttpContext.Current.Response.AddHeader("Cache-Control", "private, no-cache");
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=\"files.json\"");
HttpContext.Current.Response.Write(serializer.Serialize(rpc_response));
HttpContext.Current.Response.ContentType = "application/json";
HttpContext.Current.Response.StatusCode = 200;
After the object is serialized, I receive it on the other end (not a web browser), and that particular string looks like: \u003cRPC\u003e.
What can I do to prevent these (and other) characters from not being encoded properly, still being able to serialize my JSON object?
The characters are being encoded "properly"!1 Use a working JSON library to correctly access the JSON data - it is a valid JSON encoding.
Escaping these characters prevents HTML injection via JSON - and makes the JSON XML-friendly. That is, even if the JSON is emited directly into JavaScript (as is done fairly often as JSON is a valid2 subset of JavaScript), it cannot be used to terminate the <script> element early because the relevant characters (e.g. <, >) are encoded within JSON itself.
The standard JavaScriptSerializer does not have the ability to change this behavior. Such escaping might be configurable (or different) in the Json.NET implementation - but, it shouldn't matter because a valid JSON client/library must understand the \u escapes.
1 From RFC 4627: The application/json Media Type for JavaScript Object Notation (JSON),
Any character may be escaped. If the character is in the Basic Multilingual Plane (U+0000 through U+FFFF), then it may be represented as a six-character sequence: a reverse solidus, followed by the lowercase letter u, followed by four hexadecimal digits that encode the character's code point ..
See also C# To transform Facebook Response to proper encoded string (which is also related to the JSON escaping).
2 There is a rare case when this does not hold, but ignoring (or accounting for) that..

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.

getting the content of an invalid Xml Document in Biztalk

I have a Biztalk orchestration that posts to a http site. the response that comes back is of xmlDocument type, but it only contains a 0, no html/xml at all. All I want to do is set that 0 to a string or something to output it, but I cannot use any of the xmldocument functions because the xml is not well formed, and I cant use maps because there is no schema to work with. Trying to use any xml function returns an "invalid root level" error.
You can use a string variable and use Xpath to set the value from the response message in an Expression Shape.
You can use a XMLDocument Message and create it in an Assign Shape. You can assign the string variable to an element in the message.
You might look at using a Pipeline Component to wrap the response - e.g. have a look at the Flat File samples here

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.

Resources