I have been using Json.NET to serialize my objects in memory to json. When I call the following lines of code:
string json = JsonConvert.SerializeObject(template, Formatting.Indented);
System.IO.File.WriteAllText(file, json);
I get the following in a text file:
{
"template": {
"title": "_platform",
"description": "Platform",
"queries": [
{
"query": "// *******************************\n// -- Remove from DurationWindow at the end \n// *******************************\t\n"
}
],
"metadata": ""
}
}
a query is an object I pulled out of the database, that has a string value. When I use xml and write to file (Using XDocument), the new lines in the string (as well as the \t) are properly resolved into tabs and new lines in the file. Is it possible to get the same effect here with json.Net ?
The line-break and tab chars are not valid in JSON values, and JSON.net won't render \t and \n into tab & line break characters actually. To display this nicely, you could do:
var withLineBreaks = json.Replace("\\n", "\n").Replace("\\t", "\t");
However if you do that, the text that you're writing will be invalid JSON, and you'll have to strip out tab and line breaks when you read it back if you want to deserialize it.
Related
I am trying to convert XML with special characters (Tab) to Json for below xml :
<Request>
<HEADER>
<uniqueID>2019111855545921230</uniqueID>
</HEADER>
<DETAIL>
<cmnmGrp>
<coNm>IS XYZ INC.</coNm>
<embossedNm>ANNA ST UART</embossedNm>
<cMNm>ST UART/ANNA K</cMNm>
<cmfirstNm>ANNA</cmfirstNm>
<cmmiddleNm>K</cmmiddleNm>
<cm2NdLastNm>ST UART</cm2NdLastNm>
</cmnmGrp>
</DETAIL>
</Request>
I am getting below output in Json :
{
"Request": {
"HEADER": { "uniqueID": "2019111855545921230" },
"DETAIL": {
"cmnmGrp": {
"coNm": "IS XYZ INC.",
"embossedNm": "ANNA ST\t\tUART",
"cMNm": "ST\t\tUART/ANNA K",
"cmfirstNm": "ANNA",
"cmmiddleNm": "K",
"cm2NdLastNm": "ST\t\tUART"
}
}
}
}
Above response contains special characters. How can I remove \t which is coming for tab spaces. I am using below code for xml to Json conversion :
var xml = #"Input xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
string json = JsonConvert.SerializeXmlNode(xmlDoc, Newtonsoft.Json.Formatting.None);
I am expecting final Json output as below :
{
"Request": {
"HEADER": { "uniqueID": "2019111855545921230" },
"DETAIL": {
"cmnmGrp": {
"coNm": "IS XYZ INC.",
"embossedNm": "ANNA ST UART",
"cMNm": "ST UART/ANNA K",
"cmfirstNm": "ANNA",
"cmmiddleNm": "K",
"cm2NdLastNm": "ST UART"
}
}
}
}
Can anyone help with this.
Thanks.
Don't confuse data and representation!
ANNA ST\t\tUART - is a JSON representation of the string "ANNA ST UART".
Do now JSON parsing and you will get a string without \t.
var obj = JObject.Parse(json);
var value = obj["Request"]["DETAIL"]["cmnmGrp"]["embossedNm"];
Console.WriteLine(value); // ANNA ST UART
\t is not just fixed amount of spaces, it depends on the position from the start of the line and reader's setting of max tab size in spaces (usually 8). If you expect them to appear in JSON like they appear in XML, then you have to read the XML file in text format and programmatically replace tabs with spaces according to their position before converting to JSON. Assuming you know reader's max tab size: it could be 4.
Below are two identical lines with the same "abc\t" value with assumption of max 8 spaces per tab:
<value>abc </value>
<value>abc </value>
Generally, keeping tabs is correct, although it doesn't work for you.
JSON spec defines tabs as two characters \t, and your snapshot is correct. If you retrieve a value containing \t, they should be replaced by tab characters by JSON parser. Depends on what you need; if you don't mind the initial tab positions in XML file, you may be OK already.
I have a requirement in c# to extract the below JSON error message and read the title element.
I need to remove all the characters in the string and I want only starting from errors
i.e
{
"errors":
[{
"status": "404",
"title": "Not found data",
"detail": "This is a sample line of error detail."
}]
}
Please note that the exception can be anything so I just require to extract the JSON message starting from"errors".
Can you please assist me?
Code
string sb="{465F6CE7-3DF9-4BAF-8DD0-3E116CDAC9E7}0xc0c0167a0System.Net.WebException: There was no endpoint listening at http://TestData/member that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
{ "errors": [ { "status": "404", "title": "Not found data","detail": "This is a sample line of error detail." } ] }";
If you're asking how to extract a specific sequence of text from a random string of text, this sounds like a regular expression.
The lazy mans solution:
If you're just looking to read the title, you could just do IndexOf on "title", and then read to the next quotation mark that's not preceded by a backward-slash.
var pattern = #"\{(\s?)\'errors.*";
string sb = "{465F6CE7-3DF9-4BAF-8DD0-3E116CDAC9E7}0xc0c0167a0System.Net.WebException: There was no endpoint listening at http://TestData/member that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details. { 'errors': [ { 'status': '404', 'title': 'Not found data','detail': 'This is a sample line of error detail.' } ] }";
MatchCollection matches = Regex.Matches(sb, pattern);
I have changed the " to ', so just change the pattern to match ".
matches is not an array of all matches matches[0] will give you what you want.
You can use JSON.NET. So, you need to parse your string into JObject i.e.
string sb = #"{ ""errors"": [ { ""status"": ""404"", ""title"": ""Not found data"",""detail"": ""This is a sample line of error detail."" } ] }";
JObject jsonObject = JObject.Parse(sb);
JArray errors = (JArray)jsonObject["errors"];
foreach(var item in errors.Children())
{
int itemStatus = (int)item["status"];
string itemTitle = (string)item["title"];
string itemDetail = (string)item["detail"];
}
So, in this loop you can get what you want i have shown all the elements from the JSON that can be extracted.
Hope this helps you :)
I'm having a string that could look like this:
{
"acl_gent": {
"cluster": [],
"indices": [{
"names": ["am*"],
"privileges": ["read", "view_index_metadata"],
"query": "{\"match\": {\"ACL\": \"acl_gent\"}}"
}],
"run_as": []
},
"acl_luik": {
"cluster": [],
"indices": [{
"names": ["am*"],
"privileges": ["read", "view_index_metadata"],
"query": "{\"match\": {\"ACL\": \"acl_luik\"}}"
}],
"run_as": []
}
}
and I would like to split it up in to 2 strings, 1 containing the acl_gent and one conaining acl_luik
the string above can contain more then 2 acl's (and I DON'T know what the name will be)
so I started removing the first and last bracketes :
input = input.Substring(1, input.Length - 2);
but then I can't figure out on how to find the right closing bracket to extract the data.
this was the closest I got
private int closer(string input) {
var i = input.IndexOf('}');
Console.WriteLine(string.Format("[DEBUG] Checking: {0}", input.Substring(0, i).Contains('{')));
if (input.Substring(0, i).Contains('{')) {
return i + closer(input.Substring(i)) + 2;
}
return i;
}
What you have there is a JSON string, a common response from a web service, and there are plenty of libraries to parse JSON, the most common one being JSON.NET. With this you could do something like
JObject myJsonObject = JObject.Parse(myResponse)
and retrieve your strings by their key names, such as
JObject aclString = myJsonObject["acl_luik"];
There are plenty of resources online for parsing JSON strings if you wish to go into more detail.
You have 2 options here:
1) Parse as JSON and get the first 2 objects, this is the better one.
2) Parse using Stack as string of tokens to get what you want, like this:
- Remove the first and last { }
- Using stack, add all { you find, and once you find } remove the first { in the stack.
- Once the stack is empty then you get 1 complete object there, save the indeces while you work and it should be easy to substring with start and end.
I ran into the same problem recently. My solution was to deserialize the string to a json object (in my case a JObject using Json.net) and then accessing the individual members and serializing them to separate strings.
using Newtonsoft.Json.Linq;
public void MakeStrings(string json)
{
var jobject = JsonConvert.DeserializeObject<JObject>(json);
string acl_gent = JsonConvert.SerializeObject(jobject["acl_gent"]);
string acl_luik = JsonConvert.SerializeObject(jobject["acl_luik"]);
}
I put data table into json string using newtonsoft json. this is part of the result string,
[{"SHIP-CD;SHIP-NAME;CABIN NUMBER;CATEGORY CODE;CATEGORY DESC;MIN OCCUPANCY;MAX OCCUPANCY;PHYSICALLY CHALLENGED;DECK CODE;DECK DESC;START DATE VALIDATION;END DATE VALIDATION;OBS-VIEW;BED-ARRMNT;":"AR;MSC ARMONIA;9152;B2;Balcony Fantastica;1;3;no;AMET;Ametista;14/03/16;31/03/17;NO;L:2|U:1;"},{"SHIP-CD;SHIP-NAME;CABIN NUMBER;CATEGORY CODE;CATEGORY DESC;MIN OCCUPANCY;MAX OCCUPANCY;PHYSICALLY CHALLENGED;DECK CODE;DECK DESC;START DATE VALIDATION;END DATE VALIDATION;OBS-VIEW;BED-ARRMNT;":"AR;MSC ARMONIA;9189;B2;Balcony Fantastica;1;3;no;AMET;Ametista;14/03/16;31/03/17;NO;L:2|U:1;"},
how can I extract objects ,data from this.it comes all together.as an example think about below
{"SHIP-CD;SHIP-NAME;CABIN NUMBER;CATEGORY CODE;CATEGORY DESC;MIN OCCUPANCY;MAX OCCUPANCY;PHYSICALLY CHALLENGED;DECK CODE;DECK DESC;START DATE VALIDATION;END DATE VALIDATION;OBS-VIEW;BED-ARRMNT;":"AR;MSC ARMONIA;9189;B2;Balcony Fantastica;1;3;no;AMET;Ametista;14/03/16;31/03/17;NO;L:2|U:1;"}
in above part
SHIP-CD :"AR",
SHIP-NAME:"MSC ARMONIA",
like that. please help me with this.
Bill, I would recommend to change the way you put data into json. In the way you do it, you have the same key multiplied by the number of entries you get instead of having the key only one time.
Also, why not try to split the key components? In this way you don't have to process strings and you can easily translate them into a dictionary.
"array": [
{
"SHIP-CD": "AR;MSC ARMONIA",
"SHIP-NAME": "MSC ARMONIA",
"CABIN NUMBER": 9189,
"..."
},
{
"SHIP-CD": "AR;MSC ARMONIA",
"SHIP-NAME": "MSC ARMONIA",
"CABIN NUMBER": 9189,
"..."
},
...
]
I am sterilizing a JSON.Net object, and it contains many arrays. Here is the output I currently get:
"children": [
{
"children": [
{
},
{
}
}
However, just for the ease of reading and comparing, I would like to remove the line breaks between each brace and bracket and between the comma and next brace, so it looks like this:
"children": [ {
"children": [ {
}, {
}
}
I am already sterilizing my JSON with the Formatting.Indented argument, so I would like to know if there is another setting I can change so that JSON.Net sterilizes without the extra line brakes, but retaining the indented formatting.
There is no feature in Json.NET to give you that kind of indentation. You'll either have to do it yourself outside of Json.NET or modify the source code.
Can you split on '{' and then join the array again by spaces?