JSON Object with Slashes in it - json

I am serializing to a json object using:
public static string ToJson(this object obj)
{
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
return jsonSerializer.Serialize(obj);
}
However when I'm populating a hidden field, I'm getting the slashes with it:
"[{\"ImageLink\":\"\",\"ShowOnHomePage\":null,\"Type\":\"AdListItem\",\"Key\":null,\"Title\":\"dsafdsaf\",\"Url\":\"fdsafdsa\",\"ContentSummary\":\"\u003cdiv\u003efdsafdsa\u003c/div\u003e\"},{\"ImageLink\":\"\",\"ShowOnHomePage\":null,\"Type\":\"AdListItem\",\"Key\":null,\"Title\":\"hddfg\",\"Url\":\"dsaf\",\"ContentSummary\":\"\u003cdiv\u003efdsafdsa\u003c/div\u003e\"},{\"ImageLink\":\"\",\"ShowOnHomePage\":null,\"Type\":\"AdListItem\",\"Key\":null,\"Title\":\"asfd\",\"Url\":\"asdf\",\"ContentSummary\":\"\u003cdiv\u003eafds\u003c/div\u003e\"}]"
How would I properly get rid of the \" and replace them with just " ???
Any Ideas?
Thanks.

The slashes are Javascript string escape characters.
\" -> " so you can have a quote with-in a quote.
This is true for most all C-style languages (C, C++, C#, Java, etc)

Related

Parsing JSON in Delphi with slashes

I receive JSON strings from a WebService with slashes in it.
When I parse them, Delphi adds backslashes.
V := TJSONObject.ParseJSONValue( '{"Kode":"ABC/123" }') ;
V.ToString returns : {"Kode":"ABC\\/123"}
What is best practice to parse JSON strings in Delphi?
And why does the function V.Value always returns an empty string?
In the unit System.JSON, I see the following code:
function TJSONAncestor.Value: string;
begin
Result := '';
end;
Do I need to add code myself to System units that ship with Delphi?
\ is required to be escaped as \\, so your claim that "Just removing the backslash in the result does not work, because the value could also be "ABC\123"" is wrong, as it would have to be "ABC\\123" instead.
The only other character required to be escaped is " as \". / is certainly not required to be escaped, but it MAY be escaped at the discretion of the implementation. It is not invalid to do so. As to WHY ToString() does that, you would have to ask Embarcadero.
If you needed to, you could easily do a search-and-replace of \/ into / without affecting other escape sequences, like \\ and \". Or, try using ToJSON() instead of ToString().
Regarding TJSONAncestor.Value(), TJSONAncestor is a base class, and its Value() is a virtual method that returns a blank string by default. Descendant classes (JSONString, TJSONNumber, etc) can override Value() to return more meaningful strings. But in your example, your input string represents a JSON object, so V will be pointing at a TJSONObject instance, and TJSONObject does not override Value() because it does not make sense for an object to be represented by a string. This is even documented behavior:
http://docwiki.embarcadero.com/Libraries/en/System.JSON.TJSONAncestor.Value
Returns the string representation of a simple JSON element like a string, number or boolean.
For structured JSON elements like an object and array returns empty string.

Enumerating of JObject of NewtonSoft.Json loses '\' character in C#

I would like to parse json string using JObject.Parse() of NewtonSoft.Json. Assume that the json string is like this:
{"json":"{\"count\":\"123\"}"}
The result of jObject.First.ToString() is "json": "{\"count\":\"123\"}".
The result of jObject["json"].ToString() is {"count":"123"}. Enumerating gets the same result as this.
The testing code I used is like this.
[TestMethod()]
public void JsonParseTest()
{
var json = "{\"json\":\"{\\\"count\\\":\\\"123\\\"}\"}";
var jObject = JObject.Parse(json);
Console.WriteLine($"json : {json}");
Console.WriteLine($"jObject.First.ToString() : {jObject.First}");
Console.WriteLine($"jObject[\"json\"].ToString() : {jObject["json"]}");
}
We can see that enumerating of jObject will lose the character '\'. What is the problem? I would be appreciated for any suggestion :)
EDIT 1
The version of NewtonSoft is 12.0.3 released in 2019.11.09.
The parser isn't loosing anything. There is no literal \ in your example. The backslashes are purely part of the JSON syntax to escape the " inside the string vlue. The value of the key json is {"count":"123"}.
If you want to have backslashes in that value (however I don't see why you would want that), then you need add them, just like you added them in your C# string (C# and JSON happen to have the same escaping mechanism):
{"json":"{\\\"count\\\":\\\"123\\\"}"}
with leads to the C# code:
var json = "{\"json\":\"{\\\\\\\"count\\\\\\\":\\\\\\\"123\\\\\\\"}\"}";

How to remove backslash from JSON string using object mapper

Here is the code of getting Json string from object using object mapper:
let jsonString = Mapper().toJSONString(freechargeRequest)
but the output is coming with backslash as follows:
"{\"region\":\"http:\/\/testrm.getquickride.com:8080\/dishaapiserver\/qr_freecharge_failure.do\",\"merchantId\":\"8mILp0KGOdEG57\",\"productInfo\":\"auth\",\"mobile\":\"1357924680\",\"channel\":\"IOS\",\"amount\":\"200\",\"surl\":\"http:\/\/testrm.getquickride.com:8080\/dishaapiserver\/qr_freecharge_success.do\",\"merchantTxnId\":\"510420180705115938\"}"
I wanted the output without backslashes in JSON string.

.Net Protocol Buffers to JSON, JsonFormatReader class does not handle outmost curly braces?

I am working on using Google Protocol Buffers, using the protobuf-csharp-port library (https://code.google.com/p/protobuf-csharp-port/).
The Google.ProtocolBuffers.Serialization class has a JsonFormatReader / JsonFormatWriter class, when I use them they do not place beginning and ending curly braces to the JSON document, nor they can read the same document they write if I add beginning and ending braces.
So for example Calling
PB.ProtoBufMessage message = CreateMyMessage();
string json;
using (StringWriter sw = new StringWriter())
{
ICodedOutputStream output = JsonFormatWriter.CreateInstance(sw);
message.WriteTo(output);
output.Flush();
json = sw.ToString();
}
Creates:
"\"field1\":\"prop1\",\"field2\":1,\"subitem\":{\"x\":0,\"y\":0,\"z\":0}"
If I try to parse
String jsonmessage = "{\"field1\":\"prop1\",\"field2\":1,\"subitem\":{\"x\":0,\"y\":0,\"z\":0}}"
using
PB.ProtoBufMessage copy;
ICodedInputStream input = JsonFormatReader.CreateInstance(jsonmessage);
copy = PB.ProtoBufMessage.CreateBuilder().MergeFrom(input).Build();
I get the following:
(1:1) error: Unexpected token '{', expected: '"'.
at Google.ProtocolBuffers.Serialization.JsonCursor.Assert(Boolean cond, Char expected)
at Google.ProtocolBuffers.Serialization.JsonCursor.Consume(Char ch)
at Google.ProtocolBuffers.Serialization.JsonCursor.ReadString()
at Google.ProtocolBuffers.Serialization.JsonFormatReader.PeekNext(String& field)
at Google.ProtocolBuffers.Serialization.AbstractReader.Google.ProtocolBuffers.ICodedInputStream.ReadTag(UInt32& fieldTag, String& fieldName)
at ...
Why is the { } missing, and is this valid JSON?
You need to write/read message start/end. Like:
output.WriteMessageStart();
message.WriteTo(output);
output.WriteMessageEnd();
Similary wilhe reading:
input.ReadMessageStart();
builder.MergeFrom(input);
input.ReadMessageEnd();
The above code works with json and binary reader/writers.

How to escape "\" from JSON string in Titanium?

I have written a native android module where i am returning Json string to JavaScript layer. But in javascript layer , i am getting this json string added with "\" for all "". How to escape this "\" from json string.
Seems that your json is not a "real JSON object" but just a String. This explain why " symbol are escaped. Try to use JSON.parse() in your javascript.
var my_json_string = "{\"my_key\": \"the_value\"}";
var my_json_object = JSON.parse(my_json_string);
// should render something like
// Object {my_key: "the_value"}