Unexpected Character when Parsing .NET-Encoded JSON with JavaScript - c#

I'm developing an ASP.NET Web Pages app, and I'm seeing a problem where the Javascript JSON.parse() method is unable to parse JSON output by the .NET Json.Encode() method. My specific problem is with the ampersand (&) character (Unicode U+0026).
For example, executing this code:
object SomeObject = new { SomeProperty = "A&B" };
Response.Write(Json.Encode(SomeObject));
In my .cshtml file results in the following content in the response:
{"SomeProperty":"A\u0026B"}
Which leads to a SyntaxError: Unexpected token u in my JavaScript:
function SomeCallback(aRequest) {
if (aRequest.status === 200) {
var lResponseJSON = JSON.parse(aRequest.Response); // Error on this line
}
}
How can I get the .NET JSON encoding and the JS JSON decoding to play nice when special characters are involved?
(Preferably, short of manually going through the stringified JSON before it's parsed to replace the unicode encodings)
EDIT: Might be worth mentioning that using Json.Write(SomeObject, Response.Output) instead of Response.Write(Json.Encode(SomeObject)) has no effect on the JSON output.

Your problem has to be somewhat different that you are showing:
When I run this code through my console:
var k = JSON.parse('{"SomeProperty":"A\u0026B"}')
console.log(k);
// Object {SomeProperty: "A&B"}
everything behaves correctly.
Though it looks strange, this is valid JSON:
{"SomeProperty":"A\u0026B"}

Related

How to include CDATA parameter into a C# soap call

I have a soap client and in order to make a call to a service of my company I need, among others, a parameter containing a CDATA string.
Simple version of the C# code I have is the following:
ServiceRef.GetArraySoapClient client = new ServiceRef.GetArraySoapClient();
String codes = #"
<Codes>
<Code><Batch>AAA</Batch><Item>YYY</Item></Code>
<Code><Batch>BBB</Batch><Item>XXX</Item></Code>
</Codes>";
client.GetArray("uname", "pword", "<![CDATA[" + codes + "]]>");
When I did the same using SoapUI, it works. But within the C# code, it gives me an error that goes like "error in the format of Code items".
I don't understand what is wrong with defining CData like this?
Okay, apparently I don't need to add something special before and after 'codes' while sending the request.

Lambda can't parse input when triggered from Kinesis

I have a C# AWS Lambda function which is being triggered from AWS Kinesis and it's failing before it even gets to my code. The error I am getting is
Unexpected character encountered while parsing value: 1. Path 'Records[0].kinesis.approximateArrivalTimestamp', line 1, position 302.: JsonReaderException
at Newtonsoft.Json.JsonTextReader.ReadStringValue(ReadType readType)
at Newtonsoft.Json.JsonTextReader.ReadAsDateTime()
I have used the method signature given in the tutorial here, which looks like this:
[LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
public void HandleKinesisRecord(KinesisEvent kinesisEvent)
{
}
Is this the correct signature I should be using? Looks like there might be a mismatch between the JSON Kinesis is sending and Lambda is expecting.

dotnetrdf xml exception using QueryWithResultSet

I have an asp.net project in which, I would like to query DBPedia.
Using the following code I am getting an error:
public string testEndpoint()
{
//TEST02
SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri("http://dbpedia.org/sparql"), "http://dbpedia.org");
string res = "";
//Make a SELECT query against the Endpoint
SparqlResultSet results = endpoint.QueryWithResultSet("SELECT ?year WHERE {dbpedia:Rihanna dbpedia-owl:birthYear ?year}");
foreach (SparqlResult result in results)
{
res = result.ToString();
Console.WriteLine(result.ToString());}
Error message: "An exception of type 'System.Xml.XmlException' occurred in dotNetRDF.dll but was not handled in user code".
Even if I handle the exception the method cannot be executed. Regarding the details it says that there is an invalid XML-version 1.1.
As the XML comes from DBPedia I don't know how to change the xml version or how else I can handle this problem.
Virtuoso, which is the triple store used behind the dbpedia SPARQL endpoint, has updated its XML result generation. They replaced the XML version 1.0 with 1.1 in this commit. This causes the exception in the dotNetRDF parser.
Later on Virtuoso reverted the changes in the XML header. Hopefully DBPedia will update their binaries soon, so the old XML header appears again in the SPARQL results.
Source: http://github.com/openlink/virtuoso-opensource/issues/405

Twitterizer2 1.2.4 Streaming API exception - Unexpected end when deserializing object

Any help would be appreciated. I'm getting an exception thrown during deserialization inside JSON.Net:
Unexpected end when deserializing object. Line 216, position 2.
My calling code:
var asyncResult = s.StartPublicStream(streamErrorCallback, statusCreatedCallback, statusDeletedCallback, eventCallback, rawJsonCallback);
Setting a breakpoint in my rawJsonCallback handler shows (what appears to be) valid JSON coming back from the API.
Added the source for Twitterizer2 and JSON.Net, looks like Twitterizer.Streaming.TwitterStream.ParseMessage(string) is failing here near line 520
var user = obj.SelectToken("user", false);
if (user != null)
{
if (statusCreatedCallback != null && user.HasValues)
{
statusCreatedCallback(JsonConvert.DeserializeObject<TwitterStatus>(ConvertJTokenToString(obj)));
}
return;
}
On the call to DeserializeObject().
Newtonsoft.Json.Serliazation.JsonSerializerInternalReader.PopulateObject() fails because the reader.TokenType == None.
I suspect there is a discrepancy between the contract type/values and the object coming back from the API, but I'm not sure how to test further. Wasn't able to get the Json.Net source to compile so I can't step through it.
The problem is that Twitterizer 2.4 is using NewtonSoft.Json v4.08, which breaks it. Install Newtonsoft.Json v4.03, and you'll be fine.
Maybe this could solve your issue. I had a simillar one when I wanted to use the twitterize with JSON.NET 4.5
I follow the steps that someone mentioned on github and then I've compiled the whole source code with the new json lib and voilá ;)

Does C# have an equivalent to JavaScript's encodeURIComponent()?

In JavaScript:
encodeURIComponent("©√") == "%C2%A9%E2%88%9A"
Is there an equivalent for C# applications? For escaping HTML characters I used:
txtOut.Text = Regex.Replace(txtIn.Text, #"[\u0080-\uFFFF]",
m => #"&#" + ((int)m.Value[0]).ToString() + ";");
But I'm not sure how to convert the match to the correct hexadecimal format that JS uses. For example this code:
txtOut.Text = Regex.Replace(txtIn.Text, #"[\u0080-\uFFFF]",
m => #"%" + String.Format("{0:x}", ((int)m.Value[0])));
Returns "%a9%221a" for "©√" instead of "%C2%A9%E2%88%9A". It looks like I need to split the string up into bytes or something.
Edit: This is for a windows app, the only items available in System.Web are: AspNetHostingPermission, AspNetHostingPermissionAttribute, and AspNetHostingPermissionLevel.
Uri.EscapeDataString or HttpUtility.UrlEncode is the correct way to escape a string meant to be part of a URL.
Take for example the string "Stack Overflow":
HttpUtility.UrlEncode("Stack Overflow") --> "Stack+Overflow"
Uri.EscapeUriString("Stack Overflow") --> "Stack%20Overflow"
Uri.EscapeDataString("Stack + Overflow") --> Also encodes "+" to "%2b" ---->Stack%20%2B%20%20Overflow
Only the last is correct when used as an actual part of the URL (as opposed to the value of one of the query string parameters)
HttpUtility.HtmlEncode / Decode
HttpUtility.UrlEncode / Decode
You can add a reference to the System.Web assembly if it's not available in your project
I tried to do full compatible analog of javascript's encodeURIComponent for c# and after my 4 hour experiments I found this
c# CODE:
string a = "!##$%^&*()_+ some text here али мамедов баку";
a = System.Web.HttpUtility.UrlEncode(a);
a = a.Replace("+", "%20");
the result is:
!%40%23%24%25%5e%26*()_%2b%20some%20text%20here%20%d0%b0%d0%bb%d0%b8%20%d0%bc%d0%b0%d0%bc%d0%b5%d0%b4%d0%be%d0%b2%20%d0%b1%d0%b0%d0%ba%d1%83
After you decode It with Javascript's decodeURLComponent();
you will get this:
!##$%^&*()_+ some text here али мамедов баку
Thank You for attention
System.Uri.EscapeUriString() didn't seem to do anything, but System.Uri.EscapeDataString() worked for me.
Try Server.UrlEncode(), or System.Web.HttpUtility.UrlEncode() for instances when you don't have access to the Server object. You can also use System.Uri.EscapeUriString() to avoid adding a reference to the System.Web assembly.
For a Windows Store App, you won't have HttpUtility. Instead, you have:
For an URI, before the '?':
System.Uri.EscapeUriString("example.com/Stack Overflow++?")
-> "example.com/Stack%20Overflow++?"
For an URI query name or value, after the '?':
System.Uri.EscapeDataString("Stack Overflow++")
-> "Stack%20Overflow%2B%2B"
For a x-www-form-urlencoded query name or value, in a POST content:
System.Net.WebUtility.UrlEncode("Stack Overflow++")
-> "Stack+Overflow%2B%2B"
You can use the Server object in the System.Web namespace
Server.UrlEncode, Server.UrlDecode, Server.HtmlEncode, and Server.HtmlDecode.
Edit: poster added that this was a windows application and not a web one as one would believe. The items listed above would be available from the HttpUtility class inside System.Web which must be added as a reference to the project.

Categories

Resources