Prettify JSON before storing to TXT - c#

I'm trying to figure out how to prettify when the JavaScriptSerializer serializes my custom object to json.
string json = _jsonSerializer.Serialize(listToSerializeToJson);
it is just one long string right now, not formatted.

I don't see an option for that on the built-in JavaScriptSerializer class. However, if you're using Json.Net you can do this.
string json=JsonConvert.Serialize(listToSerializeToJson, Formatting.Indented);
According to Json.Net's project page, JavaScriptSerializer and DataContractJsonSerializer do not support creating indented prettified JSON strings.

If it's just for testing/human readability, I like using Json Lint: http://jsonlint.com/.

Related

Is it possible to extract the JSON schema from a JSON string?

I have a bunch of JSON strings, and would like to identify the schema of each one. This will allow me to keep a count of the different types of JSON objects in my collection of JSON strings.
I do not know the structure of these JSON strings ahead of time, and thus do not have a PONO to try to deserialize to.
I am currently using json.net, but am open to other options.
You could also use NJsonSchema for that,
see https://github.com/RSuter/NJsonSchema/wiki/SampleJsonSchemaGenerator
Previously JSchema was in JSON.NET Library but now its deprecated and they moved it to another library .. You Can Use Json.NET Schema ..It will easily Give You Schema of Any JSON String..even You Can Parse any JSON Using this Lib. ..like Suppose You Have JSON String ie _strJSON
JSchema schema = JSchema.Parse(_strJSON);

Escape characters after Serializing using Json

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.

JavaScriptSerializer Invalid JSON primitive

When I use the JavaScriptSerializer in C# I'm getting a "Invalid JSON primitive" exception. I assume the issue is with my json input string but I don't see the problem.
JavaScriptSerializer new JavaScjs =riptSerializer();
js.Deserialize<Object>(json)
"{\"new_name\":\"Arlington\",\"new_locationid\":\"089c6c6a-f520-e111-bdd3-00505695001f\"},{\"new_name\":\"Atlanta\",\"new_locationid\":\"0a9c6c6a-f520-e111-bdd3-00505695001f\"},{\"new_name\":\"Baltimore\",\"new_locationid\":\"0c9c6c6a-f520-e111-bdd3-00505695001f\"}"
GoBeavs:
I validated your json here: http://jsonlint.com/
Your json text is wrong: you must enclose it with brackets ([]) when you have an array of json's. It must looks like this:
"[{\"new_name\":\"Arlington\",\"new_locationid\":\"089c6c6a-f520-e111-bdd3-00505695001f\"},{\"new_name\":\"Atlanta\",\"new_locationid\":\"0a9c6c6a-f520-e111-bdd3-00505695001f\"},{\"new_name\":\"Baltimore\",\"new_locationid\":\"0c9c6c6a-f520-e111-bdd3-00505695001f\"}]"

Handling newlines in data with Json.Net

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.

How to convert json from one format to another

I have a control that expects JSON in a particular format. I have a service that spits out JSON in a different format. What's the best way to convert the JSON to the expected format? C#, jQuery? I think I'd prefer to do it server-side.
With C# you can use System.Web.Script.Serialization.JavaScriptSerializer to parse your JSON string to an object or IDictionary.
MSDN: JavaScriptSerializer Class (System.Web.Script.Serialization)
With that object you could do anything you like, change values or maybe just parse it back to something like XML.

Categories

Resources