I have a Web Api project and a controller receives a Json parameter like this
public HttpResponseMessage QueryRead([System.Web.Http.ModelBinding.ModelBinder(typeof(WebApiDataSourceRequestModelBinder))] DataSourceRequest request, string queryparams, int qryId)
The string queryparams is actually a Json object that the client sends in the form
"{\"Supplier\":{\"name\":\"Supplier\",\"type\":\"PK\",\"textvalue\":\"[{\"Supplier_Key\":2,\"Supplier_Value\":\"Foxes Beverages \"}]\",\"value\":\"[2]\"}}"
This is a valid json object.
The problem is that the string queryparams removes all backslashes and the string becomes
{"Supplier":{"name":"Supplier","type":"PK","textvalue":"[{"Supplier_Key":2,"Supplier_Value":"Foxes Beverages "}]","value":"[2]"}}
It ommits all backslashes and the later is not a valid json
Any ideas?
If your client is really sending you
"{\"Supplier\":{\"name\":\"Supplier\",\"type\":\"PK\",\"textvalue\":\"[{\"Supplier_Key\":2,\"Supplier_Value\":\"Foxes Beverages \"}]\",\"value\":\"[2]\"}}"
...the trouble is at the client end. It looks like double-encoded JSON, as though they'd done this (in JavaScript):
var json = JSON.stringify(originalObject);
var json2 = JSON.stringify(json);
...but the textvalue part is wrong even for double-encoded JSON, so it's not that simple. So if (again) they're really sending that to you, the problem is at their end. Moreover, you can't correct it. If it were "just" double-encoded JSON, you could correct for it by parsing it twice. But it isn't, because of the value of textvalue, so it's nonsense (if it's really like that).
Related
so I have a json string within my model data that is sent to the view for display in a table.
I am wanting to be sure it is displayed in a formatted fashion instead of one line string.
My research has led me to find this to be the cleanest method...
string json = JsonConvert.SerializeObject(account, Formatting.Indented);
however, within the view, once my value is extracted to #item.requestExample (the json string to be formatted), can I can call this c# to return the formatted string to the html?
btw, I've tried a few other methods just js, but every time the #item.requestExample is used within the , the inspect/console complains of the invalid tokens of the string since the string it an html representation that is using "e; instead of "'s.
tia
Maybe you could parse the json (if it is json, I'm not sure I understood well) string into a dynamic object. Then you can iterate over the properties and visualize them at your will.
You can see how to do that here.
Deserialize JSON into C# dynamic object
I'm developing a program, I know how to de-serialize a JSON. But I don't know how to de-serialize it when it's just one string in quotes.
When I request the JSON, and put it into a string, then write it to the console.
I get this:
How do I remove those quotes so it's just a normal string?
The API Documentation has this:
Response
Returns 201 Created if succeeds, 401 Unauthorized otherwise.
Returns user's authentication token as a JSON string (i.e. in double quotes). This token must be used as the auth_token parameter for methods that require authentication.
For the auth_token to work I need to remove the double quotes from that string.
Now, this may not have anything to do with JSon as I see now.
How do I remove those double quotes?
How do I remove those double quotes?
You don't want to. You want to parse it. You do that like you do with any JSON, using NewtonSoft.Json:
var token = JsonConvert.DeserializeObject<string>("\"foo\"");
Yields the string foo.
I wanna send JSON response to browser that requested based on REST service. I use something like this that includes some quotes in Controller Method:
return Json("blah\"blah", JsonRequestBehavior.AllowGet);
And I expect the result would be blah"blah But is blah\"blah and includes back slash too! I wanna have blah"blah in response without any conversion in client side. I know that need to perform this via C# codes but how to do that?
C# and JSON encode characters similarly. The string blah"blah is encoded in both C# and JSON as "blah\"blah". It's perfectly expected, then, that your raw JSON includes the backslash.
When you decode that string with a proper JSON library, it again becomes the string blah"blah.
I found the answer in two above threads:
ASP.Net MVC: how to create a JsonResult based on raw Json Data
How to output Json string as JsonResult in MVC4?
So that I need to use something like this:
return Content(jsonStringFromSomewhere, "application/json");
With this in mind considering that JSONP is used in case of ajax requesting to external service or URL. But I wanna build specific string due to parse with a special parser and I used JSON rather than JSONP and result was great.
Is there any way to handle newlines in JSON.NET. I have some data coming back with Carriage Return Line Feed in it and Json.Net is just leaving it raw in the return value. Is there a way to force Json.Net to encode this for Json. I assumed this would happen by default but it is not happening for me. Maybe I am missing something else.
I am using Json.Net in a MVC4 WebApi project if that matters.
My data is coming back with \r\n in the string such as
"Keywords": "These are my keywords.\r\n\r\n\r\nThis is a second line...\r\n\r\nThis is a third line. ...\r\n\r\n\r\nThis is a 4th line ..."
From what I understand, that should be
\\r\\n. It could be a problem with the data I am returning, but I just wanted to see what JSON.NET should be doing with this.
For me, the problem was that even if the serialized Json object looked correct in the debugger, when I write it to file it gets all these literals added (i.e. backslashes are added).
What worked was to parse the obtained json as a Token, and then use the token instead.
For example:
// Serialize and convert to Token
string json = Newtonsoft.Json.JsonConvert.SerializeObject(someObject);
var token = JToken.Parse(json);
// Save to file
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(filepath, token);
I honestly do not understand why this would be needed, or if there is a better way around this. Feedback in comment is appreciated.
You can serialize your object with the option Formatting.Indented.
Like this:
string yourJsonString = JsonConvert.SerializeObject(yourObject, Formatting.Indented, new JsonSerializerSettings { });
I think this should work.
Regards.
I am using the excellent Json.Net library to serialize my entities generated by entity framework. I use the following code to do so :
using (MyVoucherEntities context = new MyVoucherEntities())
{
List<MyObject> list = context.MyObjects.ToList();
string json = JsonConvert.SerializeObject(list);
}
Everything goes well I mean, the objects are correctly serialized except one think : it adds escape characters "\" that makes me having nightmare when deserializing on the client side.
[
{
\"$id\": \"1\",
\"CreationDate\": \"\\\/Date(1293186324257+0000)\\\/\",
\"ImageUrl\": \"http:\/\/www.google.com\",
\"Title\": \"Here is a title\"
} ]
Does anybody know why and how I can get rid of these escape characters slash "\" ?
I suspect it's not actually adding escape characters at all. I suspect you're just looking at the string in a debugger, and that's adding the escaping.
Try dumping it to a file or the console.
I found the reason why I had escape characters in my string ("\"). After serializing my objects, I am returning the JSON string to the client app through a WCF. Apparently, WCF is automatically adding these characters to the string before sending it to the network. It is a default behaviour and is apparently mandatory.
As I didn't want these escape characters, the workaround is to change the return type of the service to Stream and so, returning your JSON string inside a memory stream. It works perfectly and is quite fast.
It's invalid JSON because the result of serializing a list of objects is an array, i.e., the json will start with a [ and ending with a ]. To fix this, you need to wrap the list of objects in a root object (any instance of a class or an anonymous object), so, the resulting string will start with a { and end with }.
For example:
var output = new List<object>();
var json = JsonConvert.SerializeObject(new { root = output }, Formatting.Indented);
Response.Write(json);
Does this one help? I used it in my WebService to return Json content:
private HttpContent ConvertToJsonContent(object content)
{
string jsonObject = JsonConvert.SerializeObject(content, Newtonsoft.Json.Formatting.Indented);
return new StringContent(jsonObject, Encoding.UTF8, "application/json");
}
If strings have a "\" the two "\\" will come back. You can avoid this by using Unescape
private HttpContent ConvertToJsonContent(object content)
{
string jsonObject = Regex.Unescape(JsonConvert.SerializeObject(content, Newtonsoft.Json.Formatting.Indented));
return new StringContent(jsonObject, Encoding.UTF8, "application/json");
}
I should note that you have not completely quoted the outputted stuff (I got the url to work in your answer - that should have been edited into your question rather than put as an answer). The string I got back in a file was this:
"[{\"$id\":\"1\",\"CreationDate\":\"\\\/Date(1293186324257+0000)\\\/\",\"ImageUrl\":\"http:\/\/www.c-tina.com\/MyVoucherAdmin\/Images\/shop22\/burger.jpg\",\"Title\":\"Get one burger for free\",\"Description\":\"Bla lbzlfpzkfgmzke\\rdmjdgmj\\r\\r\\rlgfpzkegmkzepk\",\"ShopId\":22,\"PromotionId\":15,\"Shop\":null,\"Features\":[],\"SingleStats\":[],\"WhatsHots\":[],\"EntityKey\":{\"$id\":\"2\",\"EntitySetName\":\"Promotions\",\"EntityContainerName\":\"MyVoucherEntities\",\"EntityKeyValues\":[{\"Key\":\"PromotionId\",\"Type\":\"System.Int32\",\"Value\":\"15\"}]}}]"
the key thing to me is that there are unescaped quotes at the front and end which makes me think that whatever is outputting it is deciding it needs to be quoted and if you are surrounding it in quotes you ahve to escape the quotes that are inside it.
Without seeing the full output its hard to say if the problem is in teh code you've quoted above to generate the JSON or if there is a problem at a later step of processing this which is causing the quoting. Have you debugged and confirmed that the output of your serialize call is definitely producing the escaped version rather than it being done at a later stage potentially? If you're not used to the debugger then pay attention to Jon Skeet's suggest of dumping it to file or console to make sure there is no confusion that way.