To format the string to convert it into JSON format - c#

I have written a code to eliminate the double quotes which is as follows,
resulted_value = "{series_name : \"" + final_resulted_series_name + "\",period_name: \"" + period_name + "\",period_final_value: \"" + period_final_value + "\"}";
Also tried with #"""variable""" but was futile, I want to eliminate the \ slash and want my every value to be inside "". Below is my obtained result.
["{series_name : \"Actual\",period_name: \"Q1 / 2013\",period_final_value: \"17\"}","\"{series_name : \\\"Actual\\\",period_name: \\\"Q1 / 2013\\\",period_final_value: \\\"17\\\"}\"","{series_name : \"Actual\",period_name: \"Q2 / 2013\",period_final_value: \"15\"}","\"{series_name : \\\"Actual\\\",period_name: \\\"Q2 / 2013\\\",period_final_value: \\\"15\\\"}\"","{series_name : \"Actual\",period_name: \"Q3 / 2013\",period_final_value: \"13\"}","\"{series_name : \\\"Actual\\\",period_name: \\\"Q3 / 2013\\\",period_final_value: \\\"13\\\"}\"","{series_name : \"Actual\",period_name: \"Q1 / 2013\",period_final_value: \"14.103\"}""]
Below is the code that I write to serialize the string value into JSON format.
modified_listofstrings.Add(resulted_value);
System.IO.File.WriteAllText(#"C:\Json\Json.json", jSearializer.Serialize(resulted_value));
also I tried this method as well
var obj = new
{
series_name = final_resulted_series_name,
period_name,
period_final_value
};
System.IO.File.WriteAllText(#"C:\Json\Json.json",jSearializer.Serialize(obj));
this eliminate backslash but only from first values and the output obtained is
[{"series_name":"Actual","period_name":"Q1 / 2013","period_final_value":"17"},"\"{series_name : \\\"Actual\\\",period_name: \\\"Q1 / 2013\\\",period_final_value: \\\"17\\\"}\"",{"series_name":"Actual","period_name":"Q2 / 2013","period_final_value":"15"},"\"{series_name : \\\"Actual\\\",period_name: \\\"Q2 / 2013\\\",period_final_value: \\\"15\\\"}\"",{"series_name":"Actual","period_name":"Q3 / 2013","period_final_value":"13"},"\"{series_name : \\\"Actual\\\",period_name: \\\"Q3 / 2013\\\",period_final_value: \\\"13\\\"}\""]
I want to eliminate backslash from all the values.
Below is the code which gives me the output,
if (xmlAttributeCollection_for_period != null)
{
var periodid = xmlAttributeCollection_for_period["periodid"];
xmlActions[j] = periodid.Value;
period_final_id = periodid.Value;
string period_name = Client.GetAttributeAsString(sessionId, periodid.Value, "name", "");
var action = xmlAttributeCollection_for_period["value"];
xmlActionsone[j] = action.Value;
period_final_value = action.Value;
values += final_resulted_series_name + ":" + period_name + ":" + period_final_value + ",";
string vals = values.Split(',')[1];
counts = values;
string[] periods = counts.Split(',');
Period1 = periods[j];
// string final_resulted_period_name = Client.GetAttributeAsString(sessionId, resulted_series_id, "name", "");
var obj = new
{
series_name = final_resulted_series_name,
period_name,
period_final_value
};
resulted_value = "{series_name : \"" + final_resulted_series_name + "\",period_name: \"" + period_name + "\",period_final_value: \"" + period_final_value + "\"}";
modified_listofstrings.Add(resulted_value);
System.IO.File.WriteAllText(#"C:\Json\Json.json", jSearializer.Serialize(resulted_value));
}
Any Help will be greatly appreciated...

I passed the obj variable to list as follows
modified_listofstrings.Add(obj);
and then serialized the list as below
jSearializer.Serialize(modified_listofstrings)
declaration were as below,
List<object> modified_listofstrings = new List<object>();
System.Web.Script.Serialization.JavaScriptSerializer jSearializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
and it gave the desired output

Related

ArgumentOutOfRangeException when I think my code should work

I'm working on a bit of code for school but I keep getting an ArgumentOutOfRangeException
With this code I'm trying to read some data from a .csv file and if it equals the name of the image I want it to remove it from the .csv file whilst keeping the structure intact.
public void checkPair(Image card1, Image card2)
{
this.Image1 = card1;
this.Image2 = card2;
if (Convert.ToString(card1.Source) == Convert.ToString(card2.Source) && (card1 != card2))
{
getPoint(card1, card2);
string path = #"Save1.csv";
var reader = new StreamReader(File.OpenRead(path));
var data = new List<List<string>>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(';');
data.Add(new List<String> { values[0], values[1]
});
}
reader.Close();
string delimiter = ";";
for (int i = 1; i < 5; i++)
{
for (int x = 0; x < 4; x++)
{
if (data[i][x] == Convert.ToString(card1.Source))
{
data[i][x] = null;
}
}
}
File.WriteAllText(path, data[0][0] + delimiter + data[0][1] + Environment.NewLine + data[1][0] + delimiter + data[1][1] + delimiter + data[1][2] + delimiter + data[1][3] + Environment.NewLine + data[2][0] + delimiter + data[2][1] + delimiter + data[2][2] + delimiter + data[2][3] + Environment.NewLine + data[3][0] + delimiter + data[3][1] + delimiter + data[3][2] + delimiter + data[3][3] + Environment.NewLine + data[4][0] + delimiter + data[4][1] + delimiter + data[4][2] + delimiter + data[4][3] + Environment.NewLine + "ready");
I have no idea why I get this error and how to fix it
Initially, I'd change your last line from
File.WriteAllText(path, data[0][0] + delimiter + data[0][1] ....
to something like
var obj1 = data[0][0];
var obj2 = data[0][1];
File.WriteAllText(path, obj1 + delimiter + obj2 .... etc)
If you over inline functions or array accessing, when you get an exception the stack trace won't be that helpful. At least you'll have an idea of the statement that caused the issue.
This technique can prove to be very helpful, if you are looking at an in exception in the logs, after the fact.

Prevent last key in string to have a comma

Having trouble figuring out how to prevent the last key in my array to not have a comma. Since its being exported to a .Json file the last key shouldn't have a ",".
I know you can detect it by using .Last();, but I can't seem to make that work. Any recommendations?
//Data Path
string dataPath = #"..\..\FileIOExtraFiles\DataFieldsLayout.txt";
string[] dataList = File.ReadAllLines(dataPath);
//save Data data
using (StreamWriter outStream = new StreamWriter(outputFolder + #"\CharacterStringData3.json"))
{
outStream.WriteLine("{");
for (int i = 0; i < dataFile.Length; i++)
{
string s = dataFile[i];
char last = s.Last();
if (s == "")
{
outStream.WriteLine("\"" + dataList[i] + "\"" + " : " + "\" \",");
}
else
{
outStream.WriteLine("\"" + dataList[i] + "\"" + " : \"" + s + "\",");
}
}
outStream.WriteLine("}");
}
Output:
{
"data1":"item1",
"data2":item2",
"lastKey":item3",//trying to remove comma from last key in array.
}
As others have pointed out, it doesn't make sense that you are building json manually, but given that this is a question more about technique, here is one approach: you could change it to this:
var commaSuffix = (i == dataFile.Length - 1) ? "," : string.Empty;
outStream.WriteLine("\"" + dataList[i] + "\"" + " : \"" + s + "\"" + commaSuffix);
The suffix would be used on every iteration except the last.
Change this
outStream.WriteLine("\"" + dataList[i] + "\"" + " : " + "\" \",");
To this
outStream.WriteLine("\"" + dataList[i] + "\"" + " : " + "\" \""+(i==dataFile.Length?",":""));
Instead of using outStream.WriteLine() at every step, store it in a string. Then you can remove the last comma from that string and write the whole string at once:
//Get last index of comma
int lastCommaIndex = outputString.LastIndexOf(',');
//Create new StringBuilder with everything before the last comma
StringBuilder sb = new StringBuilder(outputString.Substring(0,lastCommaIndex));
//Add everything after the last comma, or just add a closing brace
//sb.Append("}"); //This instead of next line
sb.Append(outputString.Substring(lastCommaIndex+1));
//Add contents of StringBuilder to the Stream
outSteam.WriteLine(sb);

To return the list in JSON format

Below is my code,
List<string> modified_listofstrings = new List<string>();
string sJSON = "";
System.Web.Script.Serialization.JavaScriptSerializer jSearializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
resulted_value = final_resulted_series_name + ":" + period_name + ":" + period_final_value;
modified_listofstrings.Add(resulted_value);
json_resultedvalue = JsonConvert.SerializeObject(resulted_value);
modified_listofstrings.Add(json_resultedvalue);
sJSON = jSearializer.Serialize(modified_listofstrings);
return sJSON;
But on following line ,
sJSON = jSearializer.Serialize(modified_listofstrings);
I am getting an error as Cannot implicitly convert type string to system.collection.generic.list
Let me fix your approach - instead of building JSON strings using your data, and then putting them into a list and trying again to serialize that, what you should do is build your data structure and then serialize it in one go.
Since I couldn't figure out the structure of the data in your post, here is an example with a different format:
public struct Person
{
public string Name;
public int Age;
public List<string> FavoriteBands;
}
The easiest way to serialize it is to use Newtonsoft JSON. If you have an object called person, then you would serialize it using
string json = JsonConvert.SerializeObject(person);
Now suppose you have a list of these objects i.e. List<Person> people = GetTheListFromSomewhere();, then you would serialize it using
string json = Newtonsoft.Json.JsonConvert.SerializeObject(people);
Go ahead and try it!
resulted_value = final_resulted_series_name + ":" + period_name + ":" + period_final_value;
This is not a valid JSON. It must have key, value format separated by comma. I guess it should be:
resulted_value = "{series_name : \"" + final_resulted_series_name + "\",period_name: \"" + period_name + "\",period_final_value: \"" + period_final_value + "\"}";
so the result should be something like this:
{series_name: "whatever_series_name_is", period_name:
"whatever_period_name_is",period_final_value:
"whatever_period_final_value_is"}

Is there any way to change date time formatting in JSON?

I'm using JSON to send data to client. However, the date fields get transformed into a timespan format like /Date(1363807800000)/.
Is there anyway to get rid of it and let server send DateTime values like 2013/7/21 3:44 PM to client?
Think of this,
var data = "/Date(1363807800000)/";
var date = new Date(parseInt(data.replace("/Date(", "").replace(")/", ""), 10));
var result = date.getFullYear() + "-" + (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-" + (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " " + (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":" + (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes());
Then, use this RegEx to validate it,
/ ^ \ d {4} - \ d { 2} - \e{2} \e{2}:\e{2}:\e{2} $ /
Hope this helps...:)
Here is a solution using Json.NET (you can install it via NuGet):
object testObject = new { Name = "TestName", DateTime = DateTime.Now };
string output = JsonConvert.SerializeObject(testObject, new IsoDateTimeConverter());
Console.Write(output);
Output:
"{\"Name\":\"TestName\",\"DateTime\":\"2013-07-21T15:01:56.2872469+03:00\"}"
In case ISO DateTime format does not work well for you, you can write your own DateTimeConverter to use with SerializeObject function.
I wrote once this, maybe you could add the string to your json ?
var getDate = function() {
var date = new Date();
var prefix = "["
+ date.getDate() + "."
+ (date.getMonth() + 1) + "."
+ date.getFullYear() + " "
+ date.toString().split(" ")[4]
+ "]";
return prefix;
};

Store sensitive information inside keepass database from c#

I have a project where I have to handle sensitive data.
How do I open a keepass database from C# to use the data?
I have downloaded the source. I will look in it to get what I need. Any other idea?
I thought about reading a KeyPass 2 database so I added a reference to KeyPass.exe in Linqpad and started to experiment. To my surprise and without any outside help (a testament to a good API), I was reading the database after only a few minutes. Here's how I did it:
var dbpath = #"C:\path\to\passwords.kdbx";
var masterpw = "Your$uper$tr0ngMst3rP#ssw0rd";
var ioConnInfo = new IOConnectionInfo { Path = dbpath };
var compKey = new CompositeKey();
compKey.AddUserKey(new KcpPassword(masterpw));
var db = new KeePassLib.PwDatabase();
db.Open(ioConnInfo, compKey, null);
var kpdata = from entry in db.RootGroup.GetEntries(true)
select new
{
Group = entry.ParentGroup.Name,
Title = entry.Strings.ReadSafe("Title"),
Username = entry.Strings.ReadSafe("UserName"),
Password = entry.Strings.ReadSafe("Password"),
URL = entry.Strings.ReadSafe("URL"),
Notes = entry.Strings.ReadSafe("Notes")
};
kpdata.Dump(); // this is how Linqpad outputs stuff
db.Close();
Here is an extension of the original answer from Ronnie - walking the keepass tree recursively. This outputs a format that jsTree can use by the way.
public static void JsonData() {
var dbpath = Web.MapPath(#"your-password-file.kdbx");
var masterpw = "Your$uper$tr0ngMst3rP#ssw0rd";
var ioConnInfo = new IOConnectionInfo { Path = dbpath };
var compKey = new CompositeKey();
compKey.AddUserKey(new KcpPassword(masterpw));
var db = new KeePassLib.PwDatabase();
db.Open(ioConnInfo, compKey, null);
//get everything
var kpdata = from entry in db.RootGroup.GetEntries(true)
select new {
Group = entry.ParentGroup.Name,
Title = entry.Strings.ReadSafe("Title"),
Username = entry.Strings.ReadSafe("UserName"),
Password = entry.Strings.ReadSafe("Password"),
URL = entry.Strings.ReadSafe("URL"),
Notes = entry.Strings.ReadSafe("Notes")
};
var kproot = db.RootGroup.Groups;
string lastGroup = "#";
uint sc = 0;
int depth = 0;
var parent = "#"; //root is # parent
foreach (var entry in kproot) {
PwGroup pwGroup = db.RootGroup.Groups.GetAt(sc);
Web.Write(" { \"id\" : \"" + (sc) + "\", \"parent\" : \"" + parent + "\", \"text\" : \"" + pwGroup.Name.HtmlEncode() + "\" },\n");
WriteChildren(pwGroup,sc+"", depth + 1);
sc++;
}
db.Close();
}
public static void WriteChildren(PwGroup pwGroup, string parentID,int depth) {
uint sc = 0;
//if(depth>3)return; //used to prevent too much recursion
foreach (var entry in pwGroup.Groups) {
var subGroup = pwGroup.Groups.GetAt(sc);
var curID = (parentID+"_"+sc);
Web.Write(" { \"id\" : \"" + curID + "\", \"parent\" : \"" + parentID + "\", \"text\" : \"" + subGroup.Name.JsEncode() + "\"},\n");
WriteChildren(subGroup, curID, depth+1);
WriteLeaves(subGroup, curID, depth);
sc++;
}
}
public static void WriteLeaves(PwGroup pwGroup, string parentID,int depth) {
uint sc = 0;
//if(depth>3)return;
var entryList = pwGroup.GetEntries(false);
foreach (var entry in entryList) {
var curID = (parentID+"_"+sc);
Web.Write(" { \"id\" : \"" + curID + "\", \"parent\" : \"" + parentID + "\", \"text\" : \"" + entry.Strings.ReadSafe("Title").JsEncode() + "\", \"password\" : \"" + entry.Strings.ReadSafe("Password").JsEncode() + "\", \"type\" : \"file\"},\n");
sc++;
}
}
Check : KeePass Password Safe (For how keepass works)
Rather use the C# System.Cryptography classes and store you data enrypted in a database or txt file...
There is a KeePass-2.05-Alpha-Source.zip,The latest version of KeePass. C# source code,1919KB
http://s.pudn.com/upload_log_en.asp?e=1781366
http://en.pudn.com/downloads175/sourcecode/windows/other/detail816102_en.html

Categories

Resources