samedi 28 février 2015

String Manipulation in C#, Avoiding the right char, wrong place

I'm developing an app thats used for receiving a feed and presenting the data in a much nicer way. Currently I fetch the string, pass the string to a method that changes it into a list to make the data more easier to access. This was working fine throughout my app until I encountered this problem.


Sample Data:



[{"FirstName":"Bill","LastName":"Jones","UserName":"ourbilly","Played":"game306","Win":1.40,"City":"UK"}]



The above data would be broken down and presented like such



KEY | Value
FirstName : Bill
LastName : Jones
UserName : ourbilly
Played : game306
Win : 1.40
City : UK


This works, this is perfect. However I've just encountered a problem.. What if the value or key itself contained : inside of it.. for example



[{"FirstName":"Bi:ll","LastName":"Jones","UserName":"our:billy","Played":"game306","Win":1.40,"City":"UK"}]



The above data would be broken down and presented like such



KEY | Value
FirstName : Bi
ll : LastName
Jones : UserName
our : billy
Played : game306
Win : 1.40
City : UK


Which is actually incorrect, I'm unsure how to tackle this problem.. Below is the code that I'm using for making this list and for clearing up the string before returning it to present



public static ListWithDuplicates FetchFieldData(string data)
{
string[] words = cleanString(data).Split(':');

var list = new ListWithDuplicates();

for (int i = 0; i < words.Length;i++)
{
list.Add(words[i], words[i + 1]);
i++;
}

return list;
}

private static string cleanString(string messyString)
{
string[] toRemove ={ "{", "}", "\\", "\"", "[", "]" };

foreach (var s in toRemove)
{
messyString = messyString.Replace(s, "");
}
messyString = messyString.Replace(",", ":");
return messyString;
}

Aucun commentaire:

Enregistrer un commentaire