Newtonsoft.Json SerializeObject without escape backslashes - c#

Given the code:
dynamic foo = new ExpandoObject();
foo.Bar = "something";
string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo);
The output is below:
"{\"Bar\":\"something\"}"
When debugging a large json document it is hard to read - using the built in features of Newtonsoft.Json (not regex or hacks that could break things) is there any way to make the output a string with the valie:
{Bar: "something"}

If this happens to you while returning the value from a WebApi method, try returning the object itself, instead of serializing the object and returning the json string. WebApi will serialize objects to json in the response by default; if you return a string, it will escape any double quotes it finds.
So instead of:
public string Get()
{
ExpandoObject foo = new ExpandoObject();
foo.Bar = "something";
string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo);
return json;
}
Try:
public ExpandoObject Get()
{
ExpandoObject foo = new ExpandoObject();
foo.Bar = "something";
return foo;
}

Try the JToken.Parse method. I've found that even though when I view JSON objects in the debugger and they are correct, when I go to manipulate them they end up being converted to literals (i.e. backslashes are added). The JToken.Parse method seems to avoid this.
var token = JToken.Parse(text);
So in the case of the original question it would be something like:
dynamic foo = new ExpandoObject();
foo.Bar = "something";
string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo);
var token = JToken.Parse(json);
//Do stuff with token -- not json string
In my case specifically the issue was that using JObject.Add(json) would not recognize that my string was json and just insert the entire string as a single property. Once converted into a Jtoken however the JSON was interpreted correctly.

What you see in debugger when looking at the json value is the string value that you should use in a C# file to obtain the same value.
Indeed you could replace
dynamic foo = new ExpandoObject();
foo.Bar = "something";
string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo);
with
string json = "{\"Bar\":\"something\"}";
without changing the program's behaviour.
Thus, to obtain a different value, you should change how JsonConvert works, but JsonConvert conforms to the JSON standard, thus forget it!
If you are not actually serializing ExpandoObject (nor any other sealed class out of your control), you can use the DebuggerDisplayAttribute on the types that you are serializing in json, to define how the object will be shown during debug (in your code, the foo instance).
But a string is a string and VisualStudio is right: double-quotes must be escaped.

Old question but I found this,
In my case, I was looking at the JSON string in a debugger and I found that was adding the escaping.
And when I printed JSON to console, it was without escape characters. Hope it helps.

Instead of using Newstonsoft.Json you should employ the JavaScriptSerializer.Serialize Method:
dynamic foo = new ExpandoObject();
foo.Bar = "something";
var js = new JavaScriptSerializer( );
string json = js.Serialize(foo);
This method produces exactly the output you are looking for. I read about it here.

Its Just simple make the return IHttpActionResult and return the object
public IHttpActionResult Get()
{
ExpandoObject foo = new ExpandoObject();
foo = //query result
return ok(foo)
}

Hey I Just simply write out put to a file
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(#"jsonGonna.txt", true))
{
file.WriteLine(json);
}
now just run the program and you will get without black slash and it good for big programs where you need to save JSON multiple times

Actually it has nothing to do with serializer. It's just because c# don't have single and double quotes concept like Javascipt does. So it can't show string with double quotes without escaping them.
But if you want to put string into html/ cshtml without any escapes you just need to tell compliler that like so:
window.MYVAR = JSON.parse('#Html.Raw(ViewBag.MyStringFromCSharp)');

In case you're getting your data from a controller view method in such a format and finding it difficult to work with in JavaScript. Below is an easy work around:
const CleanUpDifficultJSonData = difficultJSonData => {
const dummyElement = document.createElement('div');
dummyElement.innerHtml = difficultJSonData;
const cleanJSonData = JSON.parse(dummyElement.innerHtml);
return cleanJSonData;
};
const difficultJSonData = "{\"Bar\":\"something\"}";
console.log('cleanJSonData: ',
CleanUpDifficultJSonData(difficultJSonData));

[HttpGet]
public object Get(int id)
{
object result = "";
var db = new dbEntities();
var EO = new System.Dynamic.ExpandoObject() as IDictionary<string, Object>; //needed to return proper JSON without escape slashes
try
{
IEnumerable<usp_GetComplaint_Result> aRow = db.usp_GetComplaint(id);
string DBL_QUOTE = new string(new char[] { '"' });
result = "{";
foreach (usp_GetComplaint_Result oneRow in aRow)
{
System.Reflection.PropertyInfo[] properties = typeof(usp_GetComplaint_Result).GetProperties();
foreach(System.Reflection.PropertyInfo property in properties)
{
var vValue = property.GetValue(oneRow) == null ? "null" : property.GetValue(oneRow);
EO.Add(property.Name,vValue);
}
break;
}
}
catch (Exception ex)
{
result = ex.Message;
EO.Add("Error", result);
}
finally
{
db.Dispose();
}
return Ok(EO);
}

Related

Getting a specific field from a JSON string without deserializing in C#

I currently have a REST app which returns a JSON string something like:
[{error: "Account with that email exists"}]
For when an error is thrown. I don't want to deserialize it into a custom "error" object, because it seems a bit wasteful and pointless. Is there a simple way to just extract a specific field out of a JSON string without making a custom class to reflect it.
Thanks
You have a couple of options if you don't want to create a custom class, you can deserialize to dynamic:
dynamic tmp = JsonConvert.DeserializeObject(yourString);
string error = (string)tmp.error;
Or deserialize to a dictionary:
var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>();
string error = dic["error"];
No need third party libraries. Use native JavaScriptSerializer.
string input = "[{error: \"Account with that email exists\"}]";
var jss = new JavaScriptSerializer();
var array = jss.Deserialize<object[]>(input);
var dict = array[0] as Dictionary<string, object>;
Console.WriteLine(dict["error"]);
// More short with dynamic
dynamic d = jss.DeserializeObject(input);
Console.WriteLine(d[0]["error"]);
Have a look at JObject.
dynamic obj = JObject.Parse("{ myerrors: [{error: \"Account with that email exists\"}] }");
var a = obj.myerrors[0];
string error = a.error;

Parse JSON object in C# without using class

I have two string values in a JSON object. I want to call this method in same class and use the values without using class.
I am using the following method:
public JsonResult Details()
{
return Json(new { Data = "DisplayName", result = "UniqueName" });
}
I need to use this data and result value in another method.
I am getting the value like:
var Details = JsonConvert.SerializeObject(Details());
My output is:
{
\"ContentEncoding\": null,
\"ContentType\": null,
\"Data\": {
\"Data\": \"DisplayName\",
\"result\": \"UniqueName\"
},
\"JsonRequestBehavior\": 1,
\"MaxJsonLength\": null,
\"RecursionLimit\": null
}
How do I get the data and result value from this?
The method which you are using (i.e:)
public JsonResult Details()
{
return Json(new { Data = "DisplayName", result = "UniqueName" });
}
returns a JsonResult object which has a property named Data, i.e Details().Data, which contains the data your object contains. So in order to get your object's Data and result values, you need to serialize it again.
This is the full solution:
JsonResult json = Details(); // returns JsonResult type object
string ser = JsonConvert.SerializeObject(json.Data); // serializing JsonResult object (it will give you json string)
object dec = JsonConvert.DeserializeObject(ser); // deserializing Json string (it will deserialize Json string)
JObject obj = JObject.Parse(dec.ToString()); // it will parse deserialize Json object
string name = obj["Data"].ToString(); // now after parsing deserialize Json object you can get individual values by key i.e.
string name = obj["Data"].ToString(); // will give Data value
string name = obj["result"].ToString(); // will give result value
Hope this helps.
By looking at JsonConvert.SerializeObject, I guess you are using NewtonSoft dll. In that you have JObject.Parse under Newtonsoft.Json.Linq which you can import (using Newtonsoft.Json.Linq;). You can parse that json string as
var details = JObject.Parse(your_json_string);
This will give you JObject and you can get the details as
var data = details["Data"].ToString();
JsonResult already stores the object for you, under Data. It has not been serialized yet, it simply indicates to the MVC framework to serialize it to JSON when responding to a web request.
var details = Details().Data;
Of course, this will be typed as an object - which isn't too useful. You can cast it back to the anonymous type like this:
private T CastToAnonymous<T>(object obj, T anonymousType)
{
return (T)obj;
}
var details = CastToAnonymous(Details().Data,
new { Data = string.Empty, result = string.Empty });
And then you can use it like...
var data = details.Data;
var result = details.result;
And it will be type-safe.

Referring to dynamic members of C# 'dynamic' object

I'm using JSON.NET to deserialize a JSON file to a dynamic object in C#.
Inside a method, I would like to pass in a string and refer to that specified attribute in the dynamic object.
For example:
public void Update(string Key, string Value)
{
File.Key = Value;
}
Where File is the dynamic object, and Key is the string that gets passed in. Say I'd like to pass in the key "foo" and a value of "bar", I would do:
Update("foo", "bar");, however due to the nature of the dynamic object type, this results in
{
"Key":"bar"
}
As opposed to:
{
"foo":"bar"
}
Is it possible to do what I'm asking here with the dynamic object?
I suspect you could use:
public void Update(string key, string Value)
{
File[key] = Value;
}
That depends on how the dynamic object implements indexing, but if this is a Json.NET JObject or similar, I'd expect that to work. It's important to understand that it's not guaranteed to work for general dynamic expressions though.
If you only ever actually need this sort of operation (at least within the class) you might consider using JObject as the field type, and then just exposing it as dynamic when you need to.
Okay so it turns out I'm special. Here's the answer for those that may stumble across this in future,
Turns out you can just use the key like an array index and it works perfectly. So:
File[Key] = Value; Works the way I need as opposed to
File.Key = Value;
Thanks anyway!
You can do it, if you're using JObject from JSON.NET. It does not work with an ExpandoObject.
Example:
void Main()
{
var j = new Newtonsoft.Json.Linq.JObject();
var key = "myKey";
var value = "Hello World!";
j[key] = value;
Console.WriteLine(j["myKey"]);
}
This simple example prints "Hello World!" as expected. Hence
var File = new Newtonsoft.Json.Linq.JObject();
public void Update(string key, string Value)
{
File[key] = Value;
}
does what you expect. If you would declare File in the example above as
dynamic File = new ExpandoObject();
you would get a runtime error:
CS0021 Cannot apply indexing with [] to an expression of type 'ExpandoObject'

Serialize string to JSON without \0027

A fairly straightforward question. I have the following code
var json = new JavaScriptSerializer();
var test = json.Serialize("'");
Now, Visual Studio local variable watch shows that test contains a string of value "\"\\u0027\"". Is it possible, using build in ASP.NET to make Serialize(); return serialized string without \0027 format?
The desired result for test would be "\"\'\""
Thanks!
As the commenters mentioned, this really shouldn't matter because \u0027 literally represents a single quote in Javascript.
However, if this bothers you, you may want to try using JSON.NET, which leaves single-quotes in encoded strings as they are.
Try the following
var json = JsonConvert.SerializeObject(obj);
You have to use this expression to replace your JSON string after it's serialized. Here is a sample of my code along with a function I use when giving a json output.
string json = obj.ToJSON();
json = System.Text.RegularExpressions.Regex.Unescape(json);
File.WriteAllText("<DirectoryFile>.json", json);
public static string ToJSON(this object obj)
{
var serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(obj);
}

Where can I find a simple but flexible JSON parser for C#?

I need to parse some JSON to objects in C#. I've looked at Newtonsoft and JavaScriptSerializer but either I don't know how to use them well or they do a poor job at handling format that could change and are awkward for complex structures. I want something where I can do something like:
JsonObject j = Deserialize(mystring);
String[] earthColors = j.maps["earth"].colors;
And not care about the rest of the structure.
I think you should reconsider not using Json.Net
string mystring =
#"
{
""maps"": {
""earth"": {
""colors"": [
""blue"",
""green""
]
},
""moon"": {
""colors"": [
""black"",
""white""
]
}
}
";
dynamic j = JsonConvert.DeserializeObject(mystring);
foreach (var c in j.maps["earth"].colors)
{
Console.WriteLine(c);
}
Static Class Approach
Here's a generic method for converting JSON to objects (be sure to include System.Web.Script.Serialization):
public static T JsonToObject<T>(string JsonData)
{
// Deserialize the JSON into the object
JavaScriptSerializer jss = new JavaScriptSerializer();
T rf = (T)jss.Deserialize(JsonData, typeof(T));
return rf;
}
To convert an object back to JSON, use this general method:
public static string ObjectToJson<T>(T rf)
{
// Serialize the object as JSON
StringBuilder sb = new StringBuilder();
JavaScriptSerializer jss = new JavaScriptSerializer();
jss.Serialize(rf, sb);
return sb.ToString();
}
To use it, you simply create the class that matches the JSON response, then call the JsonToObject method.
JsonObject j = JsonToObject(mystring);
Dynamic Approach
For a more dynamic approach, you'll want to look at something like this:
JavaScriptSerializer jss = new JavaScriptSerializer();
var JsonObject = jss.Deserialize<dynamic>(mystring);
This will create the JsonObject dynamically, which you can then use Dictionary style accessors without necessarily needing to create the class up front. So, for the given JSON response
{ "maps": ["earth": {"colors": ["purple","chartreuse"] }] }
c class would be dynamically created that could be accessed as
JsonObject.maps["earth"].colors[0] == "purple";
JsonObject.maps["earth"].colors[1] == "chartreuse";

Categories