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.
Related
I got some trouble with a problem when use Newtonsoft json.net to deserialize json string to dictionary. It 's a case of my json string have some special character.
string jsonString = "{\"name\":\"Jones Smith\",\"age\":\"20\",\"description\":\"The one live with \"ALIGATOR\"\"}";
Dictionary<string, object> dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);
I try to find a solution in the use of json.net but i not found. So the FINAL plan is remove that "characters". So, what is the best solution for this case?
I think you can't do very much in your situation besides changing the format at the origin. The problem with your input is that there are " characters escaped the same way once in your json directly and once in your json values.
Consider the following part: "description":"The one live with "ALIGATOR""
How should a deserializer know which " should be considered part of the value or part of the json format?
I got the answer, like the last comment, that 's not valid JSON, below is valid JSON
{"name":"Jones Smith","age":"20","description":"The one live with \"ALIGATOR\""}
And all i can do is add '\' before special characters if the value of field description is "The one live with "ALIGATOR"" to make a valid JSON and convert to c# like this:
string jsonString = {\"name\":\"Jones Smith\",\"age\":\"20\",\"description\":\"The one live with \\"ALIGATOR\\"\"}
I have a string in plain text which contains brackets like JSON format as it is created using JavaScriptSerializer().Serialize() method. I need to remove brackets and collon and want to convert it into key = value, key = value format.
Need to convert
{
"account":"rf750",
"type":null,
"amount":"31",
"auth_type":"5",
"balance":"2.95",
"card":"re0724"
}
to
'account=rf750,type=null,amount=31,authe=5,balanc=2.95,card=re0724'
Well, you've got three different things going on here.
The first, and surface issue, is: how do you change the string?
Simple - you do some string substitutions, preferably using Regex. Remove the starting/ending braces, change [a]:"[b]", to [a]=[b], - or however you want the final format to look like.
The second, and slightly deeper issue is: JSON isn't just a simple list of keys=values. You can have nesting. You can have non-string data. Simply saying you want to change the JSON result to key=value,key=value,key=value, etc - is fragile. How do you know the JSON structure will be what you're expecting? JSON Serialization will serialize successfully even if you've got nested structures, non string/int data, etc. And if you want solid code that doesn't easily break, you have to figure out: how do I handle this? Can I handle this?
The third, and final thing is: you're taking a standard data format schema and figuring out how to translate it to a nonstandard data format. 90% of the time someone does that, they deserve to be shot. Seriously, spend some solid time asking yourself whether you can use the JSON as-is, and whether the process wanting key=value,key=value,etc can be changed to use an actual standardized data format.
Here is simple solution which (1) parses json to Dictionary and (2) uses String.Join and Linq Select to provide desired output:
using System.Linq;
using Newtonsoft.Json;
..
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
var str = string.Join(',', dict.Select(r => $"{r.Key}={r.Value}"));
str-variable now contains:
account=rf750,type=,amount=31,auth_type=5,balance=2.95,card=re0724
Well thanks everyone for your time and response. your answer led me towards solution and finally i found the following solution which resolved the issue perfectly.
var jObj = (JObject)JsonConvert.DeserializeObject(modelString);
modelString = String.Join("&",jObj.Children().Cast<JProperty>().Select(jp => jp.Name + "="+ HttpUtility.UrlEncode(jp.Value.ToString())));
the above code converts the JSON into a url encoded string and remove the JSON format
I'm somehow having troubles deserializing a json string into a simple List or string[] (I don't care which).
As of what I know, this is how to do this job:
JsonConvert.DeserializeObject<List<string>>(jsonString);
Here I am getting a RuntimeBinderException. It complains about the parameter, although my json string is valid and simple: a:1:{i:0;s:10:"Sahibinden";}
What you have isn't JSON is a serialized PHP object. There have been some tools that work well with this in C# but there isn't native support. If you own the PHP, then convert the object/array to JSON first. If not try the information on this question: https://stackoverflow.com/a/1923626/474702
Your JSON is invalid. Problems:
a:1 should be inside an object bracket of {}
The : before the { is invalid, you need a , there
The ; just after i:0 is invalid, you need a comma there
You repeat the mistake described in 1. and 2. inside your {} brackets as well
Solution: You need to read about JSON and make sure you understand its syntax.
Y is my object being serialized in a weird manner while using newtonsoft.json from ASP.Net Web API?
var s = JsonConvert.SerializeObject(request, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
Output string as below,
"{\"head\":{\"version\":\"1.0\",\"serial\":\"20140102,6,125\",\"skinId\":\"Test\""
I want to send Json format string to a third party rest service (they accept only Json format).
Any help is much appreciated.
Cheers
S
There's nothing to be worried about here. This is the correct serialized object json. It is appearing like this because you are viewing this in visual studio by hovering variable to view its value, because in c# \" is used to represent a " in a string. When you will write this value in a text file(just to test actual value) , you will see what is it's actual value as:
string json="{\"head\":{\"version\":\"1.0\",\"serial\":\"20140102,6,125\",\"skinId\":\"Test\"";
File.WriteAllText("c:\\tests on.txt",json) ;
You will see the json in file what you actually want.
It's because you have serialized it twice, can you post more of your code or skip calling SerializeObject completely
I doubt you are still seeking an answer, but my workaround was to create a JObject with Newtonsoft and pass that.
Either:
JObject jBytes = Object.Parse(JsonConvert.SerializeObject(myObject, MyDateTimeFmtString);
or
JObject jBytes = JObject.FromObject(myObject, MyJsonSerializer);
The first case was my second choice, but I think there is a bug in Newtonsoft where JObject.FromObject ignores the DateFormatString in JsonSerializer.
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.