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,
"..."
},
...
]
Related
I have this code
var list = new List<long>();
long id = 202;
list.Add(2000);
list.Add(2001);
list.Add(2002);
var stringOfIds = string.Join(",", list);
var paramList = #"{'ProjectId':" + id + ", 'EntityIDsList': " + stringOfIds + "}";
Console.WriteLine(paramList);
var parameters = JsonConvert.DeserializeObject<Dictionary<string, object>>(paramList);
Console.WriteLine(parameters);
for some particular reason, it doesn't Deserialize the object and it crashes. What I'm trying here to do is: transform a list of longs into a string, comma separated -> construct the paramList string and then deserialize it using Newtonsoft.Json. I believe that the error is somewhere in the stringOfIds but couldn't figure it out sadly. Do you know what am I doing wrong and how can I fix it?
Right now your paramList looks like this:
{
"ProjectId": 202,
"EntityIDsList":
2000,
2001,
2002
}
Which is not proper JSON. It should look like this:
{
"ProjectId": 202,
"EntityIDsList": [
2000,
2001,
2002
]
}
So you should change it to:
var paramList = #"{'ProjectId':" + id + ", 'EntityIDsList': [" + stringOfIds + "]}";
Also at this point Console.WriteLine(parameters); won't tell you anything meaningfull, you should probably change it to Console.WriteLine(parameters.ToString());
The string you have, paramList is not a valid JSON. JSON object has keys (and values if they are strings) surrounded with double quotes, not single quotes.
Corrected string with escaped double quotes:
#"{""ProjectId"": " + id + #", ""EntityIDsList"": """ + stringOfIds + #"""}";
If your purpose of writing this string is to convert it to an object, you should directly create an object. Also note that you cant print the objects with Console.WriteLine... you will need to convert this to a string first (JsonConvert.SerializeObject) then print it.
var parameters = new
{
ProjectId = id,
EntityIDsList = stringOfIds
};
Console.WriteLine(JsonConvert.SerializeObject(parameters, Formatting.Indented));
// output:
{
"ProjectId": 202,
"EntityIDsList": "2000,2001,2002"
}
If you want EntityIDList as a list of numbers, change the value of EntityIDsList to list instead of stringOfIds.
var parameters2 = new
{
ProjectId = id,
EntityIDsList = list
};
Console.WriteLine(JsonConvert.SerializeObject(parameters2, Formatting.Indented));
//output:
{
"ProjectId": 202,
"EntityIDsList": [
2000,
2001,
2002
]
}
You have two "problems"
you need to add extra single-quotes around the stringOfIds bit
maybe it's actually what you want, but... this will give you a dictionary with 2 items with keys: "ProjectId" and "EnitityIDsList".
As the list is stringified you may as well use D<string, string> (or dynamic, depending on what you're actually trying to do.
I'm guessing you will want to have a collection of "projects"? So the structure in the question won't work.
[
{ "1": "1001,1002" },
{ "2": "2001,2002" }
]
is the normal json form for a dictionary of items
[
{ "1": [1001,1002] },
{ "2": [2001,2002] }
]
into a D<string,List<int>> would be "better".
Strongly suggest you create classes/records to represent the shapes and serialize those. Rather than string concatenation. If you must, then try to use StringBuilder.
Also, although Newtonsoft will handle single quotes, they're not actually part of the spec. You should escape double-quotes into the string if you actually need to generate json this way.
Maybe this is just a cutdown snippet to demo your actual problem and I'm just stating the obvious :D
Just a load of observations.
The extra quotes is the actual "problem" with your sample code.
I want to save some data in a text file like this:
Name = Frank
Age = 28
Registered = False
Now i want to read/update the Data contained in each row. For example I need to change the Name to "Tim", I have to find row Name and than replace the string after the "="
Im not quiet sure how to solve this properly and i couldnt find anything on Google that satisfied me
I tried to update it with the text.Replace() method but it only chances the string it actually finds.
I expect to read the correct data out of the row and replace it if needed
There are a wide variety of ways to do this. I'll contribute one of them (which I think is simpler to understand).
Step 1: Read the entire file into a string.
Step 2: Convert it to string.
Step 3: Process the string using simple methods like split and join.
Step 4: Overwrite the previous file with the processed string.
The code is below:
if (File.Exists(your_file_path)){
string yourfile = File.ReadAllText(your_file_path);
// Now the file is a simple string that you can manipulate using
// string split functions.
// For Example:
// break by lines
string[] lines = yourfile.Split('\n');
foreach (string line in lines){
if (line.Substring(0,4) == "Name"){
// replace the necessary line
line = "Name = Tim";
break;
}
}
// Join the array again
yourfile = lines.Join("\n", lines);
File.WriteAllText(your_file_path, yourfile);
}
Try to save the file in Json format. Like
{
"Name" : "Frank"
"Age" : 28
"Registered" : False
}
Then read the file deserialize it to object by using Newtonsoft json
Then update your property(Name) serialize it to string again and then write again to the same file.
In this Approach very less chances of errors.
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 have the following data stored in DocumentDB:
{
"DocumentDbTest_AllFieldTypes": {
"#numeric": "-978623478.23434",
"#string": "test\u0000",
"#boolset": "test|test1",
"#date": "2010/12/24",
"#datetime": "2010/12/24 09:12:34",
"#time": "09:12:34",
"#richtext": "<html onload='alert(3)'>test</html>",
"#version": "2015-08-27T13:17:30:975.230",
"typename": "DocumentDbTest_AllFieldTypes",
}
"id": "56177058-eb54-4b4d-a4ee-45b9603d4c2c"
}
But when I search for it I am not getting the data back.
SELECT * FROM root.DocumentDbTest_AllFieldTypes c
WHERE c["#string"] = "test\u0000"
Does anyone know how to search for the \u000 (null character) data or similar data in DocumentDB?
This has been confirmed as a limitation. The code assumes null-terminated strings and hence would consider “test\u0000” the same as ‘test’. In short, \u0000 is currently not a supported string character in a query.
We will work on a future fix.
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.