String to Object Collection - c#

I Have this String
([{"id":"111","name":"Robocop","cover":"3114188e.jpg"},{"id":"222","name":"Eater","cover":"72dpi.jpg"}])
And is there better way to convert to Object Collection, couse now my crappy code looks like this:
var trimer = myString.TrimStart('(', '[').TrimEnd(')', ']');
string[] coll = trimer.Split('{','}');
string content = "";
foreach(string i in coll)
{
if (!string.IsNullOrEmpty(i) && i != "," && i != "")
{
content += i + "\r\n";
}
}
string[] contentData = content.Split(new string[] { "\r\n" }, StringSplitOptions.None);
for (int i = 0; i < contentData.Length - 1; i++)
{
string book = contentData[i].Replace(',','\t').Replace("\"","");
string[] info = book.Split(new string[] { "\t" }, StringSplitOptions.None);
string id = info[0];
string name = info[1];
string cover = info[2];
}

Yes. You actually have a JSON string. You'll need to remove the parenthesis (if they actually exist in the received string) and then you can deserialize it properly. This example uses Json.NET:
public void DeserializeFoo()
{
var json = "[{\"id\":\"111\",\"name\":\"Robocop\",\"cover\":\"3114188e.jpg\"},
{\"id\":\"222\",\"name\":\"Eater\",\"cover\":\"72dpi.jpg\"}]";
var foos = JsonConvert.DeserializeObject<List<Foo>>(json);
foreach (var foo in foos)
{
Console.WriteLine("Id: {0}", foo.Id);
Console.WriteLine("Name: {0}", foo.Name);
Console.WriteLine("Cover: {0}", foo.Cover);
}
}
public class Foo
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("cover")]
public string Cover { get; set; }
}

Related

C# retrieve parent-child url from full url using recursively

I need your help in getting parent-child URL list from full URL, maybe using recursively.
For example, below is URL in flat structure. I have to parse in parent-child form with inner level of child structure.
https://domain/UrlA/UrlA_L1/UrlA_L1_L2
https://domain/UrlA/UrlA_L1/UrlA2_L1_L2
https://domain/UrlB/UrlB_L1/UrlB_L1_L2
https://domain/UrlC/UrlC_L1/UrlC_L1_L2
https://domain/UrlD/UrlD_L1/UrlD_L1_L2/UrlD_L1_L2_L3
https://domain/UrlE/UrlE_L1/UrlE_L1_L2/UrlE_L1_L2_L3
https://domain/UrlF/UrlF_L1/UrlF_L1_L2/UrlF_L1_L2_L3
into a list of URL with child-parent relationship.
public class HtmlSiteMap
{
public string Url { get; set; }
public string PageTitle { get; set; }
public int UrlLevel { get; set; }
public List<HtmlSiteMap> Childrens { get; set; }
}
my expected output
{
Url: https://domain/UrlA,
PageTitle : UrlA,
UrlLevel : 0 ,
Childrens : {
Url : https://domain/UrlA/UrlA_L1,
PageTitle : UrlA_L1,
UrlLevel : 1,
Childrens : {
Url : https://domain/UrlA/UrlA_L1/UrlA_L1_L2,
PageTitle : UrlA_L1_L2,
UrlLevel : 2,
Childrens : null
},
{
Url : https://domain/UrlA/UrlA_L1/UrlA2_L1_L2,
PageTitle : UrlA2_L1_L2,
UrlLevel : 2,
Childrens : null
}
},
Url: https://domain/UrlB,
PageTitle : UrlB,
UrlLevel : 0 ,
Childrens : {
Url : https://domain/UrlB/UrlB_L1,
PageTitle : UrlB_L1,
UrlLevel : 1,
Childrens : {
Url : https://domain/UrlB/UrlB_L1/UrlB_L1_L2,
PageTitle : UrlB_L1_L2,
UrlLevel : 2,
Childrens : null
}
}
.................
.................
..................
}
I have tried to achieve by splitting and recursively. But unable to get a result. Your help will be appreciated.
Here is another reverse solution. I am working on preordered list, constructing nodes from roots to leaves. This code looks more readable and understandable by beginners in recursion.
static void Main(string[] args)
{
var input = new[]
{
new Uri("https://domain/UrlA/UrlA_L1/UrlA_L1_L2"),
new Uri("https://domain/UrlA/UrlA_L1/UrlA2_L1_L2"),
new Uri("https://domain/UrlB/UrlB_L1/UrlB_L1_L2"),
new Uri("https://domain/UrlC/UrlC_L1/UrlC_L1_L2"),
new Uri("https://domain/UrlD/UrlD_L1/UrlD_L1_L2/UrlD_L1_L2_L3"),
new Uri("https://domain/UrlE/UrlE_L1/UrlE_L1_L2/UrlE_L1_L2_L3"),
new Uri("https://domain/UrlF/UrlF_L1/UrlF_L1_L2/UrlF_L1_L2_L3")
};
var rows = input.Select(u => u.AbsolutePath.Substring(1))
.OrderBy(s => s).Select(s => s.Split('/')).ToList();
var rootNodes = new List<HtmlSiteMap>();
ProcessNodes(rootNodes, rows,
input.Select(u => $"{u.Scheme}://{u.Host}/").Distinct().FirstOrDefault(), 0);
foreach (var node in rootNodes)
Console.WriteLine(node.ToString());
}
static void ProcessNodes(List<HtmlSiteMap> children, List<string[]> rows, string prefix, int level)
{
if (rows.Count == 0)
return;
HtmlSiteMap currentNode = null;
var subRows = new List<string[]>();
foreach (var parts in rows)
{
if (parts.Length == 0)
continue;
subRows.Add(parts.Skip(1).ToArray());
if (currentNode != null && currentNode.PageTitle == parts[0])
continue;
if(currentNode != null)
ProcessNodes(currentNode.Children, subRows, prefix + currentNode.PageTitle + "/", level + 1);
currentNode = new HtmlSiteMap
{
Url = prefix + parts[0],
PageTitle = parts[0],
UrlLevel = level
};
children.Add(currentNode);
subRows.Clear();
}
if(currentNode != null && subRows.Count > 0)
ProcessNodes(currentNode.Children, subRows, prefix + currentNode.PageTitle + "/", level + 1);
}
public class HtmlSiteMap
{
public string Url { get; set; }
public string PageTitle { get; set; }
public int UrlLevel { get; set; }
//Also renamed this from Childrens to Children
public List<HtmlSiteMap> Children { get; set; }
public HtmlSiteMap()
{
Children = new List<HtmlSiteMap>();
}
//Borrowed this from previous answer
public override string ToString()
{
var shift = new string(' ', UrlLevel);
var sb = new StringBuilder();
sb.AppendLine(shift + $"Url: {Url},");
sb.AppendLine(shift + $"PageTitle: {PageTitle},");
sb.AppendLine(shift + $"UrlLevel: {UrlLevel},");
sb.AppendLine(shift + "Children:");
if (Children.Count == 0)
{
sb.AppendLine(shift + "-");
}
else
{
foreach (var child in Children)
{
sb.AppendLine(child.ToString());
}
}
return sb.ToString();
}
}
A base version (without errors handling) may look like this:
static void Main(string[] args)
{
var input = new List<string>
{
"https://domain/UrlA/",
"https://domain/UrlA/UrlA_L1/",
"https://domain/UrlA/UrlA_L1/UrlA_L1_L2",
"https://domain/UrlA/UrlA_L1/UrlA2_L1_L2",
"https://domain/UrlB",
"https://domain/UrlB/UrlB_L1",
"https://domain/UrlB/UrlB_L1/UrlB_L1_L2",
"https://domain/UrlC/UrlC_L1/UrlC_L1_L2",
"https://domain/UrlD/UrlD_L1/UrlD_L1_L2/UrlD_L1_L2_L3",
"https://domain/UrlE/UrlE_L1/UrlE_L1_L2/UrlE_L1_L2_L3",
"https://domain/UrlF/UrlF_L1/UrlF_L1_L2/UrlF_L1_L2_L3"
};
var output = new List<HtmlSiteMap>();
foreach (var url in input)
{
var parts = url.Split(#"/", StringSplitOptions.RemoveEmptyEntries);
var current = new HtmlSiteMap
{
Url = url,
PageTitle = parts[^1]
};
var parentName = parts[^2];
static HtmlSiteMap FindParent(List<HtmlSiteMap> score, string name)
{
foreach (var item in score)
{
if (item.PageTitle == name)
{
return item;
}
var inChild = FindParent(item.Childrens, name);
if (inChild != null)
{
return inChild;
}
}
return null;
}
var parent = FindParent(output, parentName);
if (parent == null)
{
current.UrlLevel = 1;
output.Add(current);
}
else
{
current.UrlLevel = parent.UrlLevel + 1;
parent.Childrens.Add(current);
}
}
foreach (var current in output)
{
Console.WriteLine(current.ToString());
}
Console.ReadLine();
}
public class HtmlSiteMap
{
public string Url { get; set; }
public string PageTitle { get; set; }
public int UrlLevel { get; set; }
public List<HtmlSiteMap> Children { get; set; }
public HtmlSiteMap()
{
Children = new List<HtmlSiteMap>();
}
public override string ToString()
{
var shift = new string(' ', UrlLevel);
var sb = new StringBuilder();
sb.AppendLine(shift + $"Url: {Url},");
sb.AppendLine(shift + $"PageTitle: {PageTitle},");
sb.AppendLine(shift + $"UrlLevel: {UrlLevel},");
sb.AppendLine(shift + "Children:");
if (Children.Count == 0)
{
sb.AppendLine(shift + "-");
}
else
{
foreach (var child in Children)
{
sb.AppendLine(child.ToString());
}
}
return sb.ToString();
}
}

Unable to get values of Object in Json array

I am facing problem with reading object values into Json array. please help me what is the problem here. Below is my code. I am sending employee list to get Json array. but i am not getting 'EmployeeDetails' in json array(that is in second level).
what is the problem here?
below is my code
class Program
{
static void Main(string[] args)
{
List<Employee> list = new List<Employee>();
Employee emp = new Employee { ID = 101, Department = "Stocks", EmployeeDetails = new Name { FirstName = "S", LastName = "Charles", Email = "abc#gmail.com" } };
Employee emp1 = new Employee { ID = 102, Department = "Stores", EmployeeDetails = new Name { FirstName = "L", LastName = "Dennis", Email = "Den#gmail.com" } };
list.Add(emp);
list.Add(emp1);
var resul1t = Program.GetEmployeeDetails(list);
}
private static string GetEmployeeDetails(List<Employee> emp)
{
string jsonarray = "";
if ((emp != null) && (emp.Count > 0))
{
Dictionary<string, object> dic = new Dictionary<string, object>();
int i = 0;
foreach (var awo in emp)
{
dic.Add(i.ToString(), ObjectToString(awo));
i++;
}
if (dic.Count > 0)
{
jsonarray = DictionnaryToArray(dic);
}
}
return jsonarray;
}
private static string ObjectToString(object obj)
{
Type objType = obj.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(objType.GetProperties());
StringBuilder sb = new StringBuilder(1024);
foreach (PropertyInfo prop in props)
{
var type = prop.GetValue(obj, null);
string attributeValueString = string.Format("\"{0}\":\"{1}\"", prop.Name, prop.GetValue(obj, null));
if (type != null && type.GetType() == typeof(double))
{
var doubleToStringValue = Convert.ToString(prop.GetValue(obj, null), System.Globalization.CultureInfo.InvariantCulture);
attributeValueString = string.Format("\"{0}\":\"{1:0.0}\"", prop.Name, doubleToStringValue);
}
sb.Append(attributeValueString).Append(";");
}
return "{" + sb.ToString().TrimEnd(new char[] { ';' }) + "}";
}
private static string DictionnaryToArray(Dictionary<string, object> data)
{
return "{" + string.Join(";", (from c in data select string.Format("\"{0}\":{1}", c.Key.ToString(), c.Value.ToString())).ToArray()) + "}";
}
}
public class Employee
{
public int? ID { get; set; }
public string Department { get; set; }
public Name EmployeeDetails { get; set; }
}
public class Name
{
public string LastName { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
}
Thanks
You could call ObjectToString recursively when you have a nested class, i'm changing little the ObjectToString, like the following code:
private static string ObjectToString(object obj)
{
Type objType = obj.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(objType.GetProperties());
StringBuilder sb = new StringBuilder(1024);
foreach (PropertyInfo prop in props)
{
string attributeValueString;
var type = prop.GetValue(obj, null);
if (type != null && type.GetType() == typeof(double))
{
var doubleToStringValue = Convert.ToString(prop.GetValue(obj, null), System.Globalization.CultureInfo.InvariantCulture);
attributeValueString = string.Format("\"{0}\":\"{1:0.0}\"", prop.Name, doubleToStringValue);
}//new code
else if (prop.PropertyType.IsNested)
{
attributeValueString = string.Format("\"{0}\":{1}", prop.Name, ObjectToString(type));
}
else
{
attributeValueString = string.Format("\"{0}\":\"{1}\"", prop.Name, type);
}
sb.Append(attributeValueString).Append(",");
}//updated code ; by ,
return "{" + sb.ToString().TrimEnd(new char[] { ',' }) + "}";
}
Note that, you need to replace ; by , to get a valid json.
Result
{
"0":{
"ID":"101",
"Department":"Stocks",
"EmployeeDetails":{
"LastName":"Charles",
"Email":"abc#gmail.com",
"FirstName":"S"
}
},
"1":{
"ID":"102",
"Department":"Stores",
"EmployeeDetails":{
"LastName":"Dennis",
"Email":"Den#gmail.com",
"FirstName":"L"
}
}
}
I hope this helps you fix the issue.

Email Generator iteration through a list

I've written a function that generates an HTML email and fills it with information from a database.
I've been trying to iterate through a list, but can't seem to get the function to be generic and run throught the Items list.
Here is the Email Generator function. It is fairly generic, so that it can be used in a wide variety of email templates.
public interface IMailObject
{
string Subject { get; }
}
public interface IEmailGenerator
{
MailMessage generateEmail(IMailObject mailObject, string htmlTemplate, string textTemplate);
}
public class EmailGenerator : IEmailGenerator, IRegisterInIoC
{
private string mergeTemplate(string template, object obj)
{
Regex operationParser = new Regex(#"\$(?:(?<operation>[\w\-\,\.]+)\x20)(?<value>[\w\-\,\.]+)\$", RegexOptions.Compiled);
Regex valueParser = new Regex(#"\$(?<value>[\w\-\,\.]+)\$", RegexOptions.Compiled);
var operationMatches = operationParser.Matches(template).Cast<Match>().Reverse().ToList();
foreach (var match in operationMatches)
{
string operation = match.Groups["operation"].Value;
string value = match.Groups["value"].Value;
var propertyInfo = obj.GetType().GetProperty(value);
if (propertyInfo == null)
throw new TillitException(String.Format("Could not find '{0}' in object of type '{1}'.", value, obj));
object dataValue = propertyInfo.GetValue(obj, null);
if (operation == "endforeach")
{
string foreachToken = "$foreach " + value + "$";
var startIndex = template.LastIndexOf(foreachToken, match.Index);
var templateBlock = template.Substring(startIndex + foreachToken.Length, match.Index - startIndex - foreachToken.Length);
var items = (IEnumerable) value;
string blockResult = "";
foreach (object item in items)
{
blockResult += mergeTemplate(templateBlock, item);
}
template = template.Remove(startIndex, match.Index - startIndex).Insert(startIndex, blockResult);
}
}
var valueMatches = valueParser.Matches(template).Cast<Match>().Reverse().ToList();
foreach (var match in valueMatches)
{
string value = match.Groups["value"].Value;
var propertyInfo = obj.GetType().GetProperty(value);
if (propertyInfo == null)
throw new Exception(String.Format("Could not find '{0}' in object of type '{1}'.", value, obj));
object dataValue = propertyInfo.GetValue(obj, null);
template = template.Remove(match.Index, match.Length).Insert(match.Index, dataValue.ToString());
}
return template;
}
public MailMessage generateEmail(IMailObject mailObject, string htmlTemplate, string textTemplate)
{
var mailMessage = new MailMessage();
mailMessage.IsBodyHtml = true;
mailMessage.Subject = mailObject.Subject;
mailMessage.BodyEncoding = Encoding.UTF8;
// Create the Plain Text version of the email
mailMessage.Body = this.mergeTemplate(textTemplate, mailObject);
// Create the HTML version of the email
ContentType mimeType = new System.Net.Mime.ContentType("text/html");
AlternateView alternate = AlternateView.CreateAlternateViewFromString(this.mergeTemplate(htmlTemplate, mailObject), mimeType);
mailMessage.AlternateViews.Add(alternate);
return mailMessage;
}
}
And here is a case of the message data:
public class MessageData : IMailObject
{
public string Property1 { get; private set; }
public string Property2 { get; private set; }
public string Property3 { get; private set; }
public string Property4 { get; private set; }
public string Property5 { get; private set; }
public string Property6 { get; private set; }
public string Subject
{
get { return this.Property1 + DateTime.Now.ToShortDateString(); }
}
public List<MessageItemData> Items { get; private set; }
public MessageData(string property1, string property2, string property3, DateTime property4, string property7, string property8, DateTime property9, DateTime property10, int property11, double property12, string property5, string property6)
{
this.Property1 = property1;
this.Property2 = property2;
this.Property3 = property3;
this.Property4 = property4.ToShortDateString();
this.Property5 = property5;
this.Property6 = property6;
this.Items = new List<MessageItemData>();
this.Items.Add(new MessageItemData(property7, property8, property9, property10, property11, property12));
}
}
public class MessageItemData
{
public string Property7 { get; private set; }
public string Property8 { get; private set; }
public string Property9 { get; private set; }
public string Property10 { get; private set; }
public int Property11 { get; private set; }
public double Property12 { get; private set; }
public MessageItemData( string property7, string property8, DateTime property9, DateTime property10, int property11, double property12)
{
this.Property7 = property7;
this.Property8 = property8;
this.Property9 = property9.ToShortDateString();
this.Property10 = property10.ToShortDateString();
this.Property11 = property11;
this.Property12 = property12;
}
}
The function works when there is only one set of elements being used. If we use the MessageData class as an example. All the information will be replaced correctly, but I'm wanting to improve the email generator function, because this particular MessageData class has a list of objects, where Property7 to Property12 will be replaced multiple times.
The function is started at: if (operation == "endforeach"), but I need some help to improve it so that it runs through the: var items = (IEnumerable) value;, so that the function returns TemplateHeader + TemplateItem + TemplateItem + ...however many TemplateItems there are + TemplateFooter. It currently will only return TemplateHeader + TemplateItem + TemplateFooter, even though there are multiple items in the list, it will only return the first item.
In this case I'm assuming I need to get the List Items. I've been trying to implement it into the EmailGenerator just below:
var items = (IEnumerable) value;
with the code:
if (propertyInfo.PropertyType == typeof(List<>))
{
foreach (var item in items)
{
Console.WriteLine(item);
}
}
Console.WriteLine is just for testing purposes, to see if I get any values in Debug(which I'm currently getting null)
Assuming the type of the Items property is the same across all instances you may want to try using IsInstanceOfType instead. And then get the value of the property via the GetValue method. Reflection can be confusing at times ;) but hopefully, it is what you are looking for.
var data = new MessageData("a", "b", "c", DateTime.Now, "d", "e", DateTime.Now, DateTime.Now, 1, 2, "f", "g");
data.Items.Add(new MessageItemData("7", "8", DateTime.Now, DateTime.Now, 11, 12));
data.Items.Add(new MessageItemData("71", "81", DateTime.Now, DateTime.Now, 111, 112));
var dataType = data.GetType();
foreach (var propertyInfo in dataType.GetProperties())
{
if (propertyInfo.PropertyType.IsInstanceOfType(data.Items))
{
foreach (var item in (List<MessageItemData>)propertyInfo.GetValue(data))
{
Console.WriteLine(item);
}
}
}

How to get specific parts of string and assign them to variables in c#?

passing a string like this to the code behind:
0,-1|1,-1|2,-1|3,-1|4,-1|5,-1|6,-1|7,-1|8,-1
I need to be able to asign the values before and after the "," symbol per each "|" symbol that exits in the string, into separated variables, "line" for first value (before the ",") and "group" for the next one (after the ",").
Right now I'm trying with this, but I'm having some issues with converting from string[] to string.
public static string GuardarGrupos(string parametro){
var data = parametro.Split(Convert.ToChar("|"));
var datos = "";
string[] linea;
var grupo = "";
//Iterate through each of the letters
foreach (var check in data)
{
datos = data[0];
linea = data[0].Split(Convert.ToChar(","));
}
return linea;
}
Any Idea how can I achieve this?
Make a class or struct to hold your values:
public class DataObject
{
public string X {get; set;}
public string Y {get; set;}
}
Return a List<T> of type DataObject
public static List<DataObject> GuardarGrupos(string parametro){
//List to return
List<DataObject> returnList = new List<DataObject>();
//Split the string on pipe to get each set of values
var data = parametro.Split('|'); //No need to do a convert.char(),
//String.Split has an overload that takes a character, use single quotes for character
//Iterate through each of the letters
foreach (var check in data)
{
//Split on comma to get the individual values
string[] values = check.Split(',');
DataObject do = new DataObject()
{
X = values[0];
Y = values[1];
};
returnList.Add(do);
}
return returnList;
}
Once you have the List<DataObject>, you can form line and group using linq and string.Join:
List<DataObject> myList = GuardarGrupos("0,-1|1,-1|2,-1|3,-1|4,-1|5,-1|6,-1|7,-1|8,-1");
string line = string.Join(",", myList.Select(x => x.X);
string group = string.Join(",", myList.Select(y => y.Y);
Instead of using local variables , create a Class that stores your retrieved values. then in the main you could handle/manipulate those values as required.
public class MyData
{
public string Datos { get; set; }
public string Linea { get; set; }
public string Grupo { get; set; }
}
public static List<MyData> myFunction(string parametro)
{
List<MyData> result = new List<MyData>();
var data = parametro.Split(Convert.ToChar("|"));
foreach (var check in data)
{
MyData temp = new MyData();
var line = check.Split(',');
temp.Datos = line[0];
temp.Linea = line[1];
temp.Grupo = check;
result.Add(temp);
}
return result;
}
static void Main(string[] args)
{
var t = myFunction("0,-1|1,-1|2,-1|3,-1|4,-1|5,-1|6,-1|7,-1|8,-1");
}
Here is a robust solution that's just a simple iteration over a string.
void Main()
{
var xs = "0,-1|1,-1|2,-1|3,-1|4,-1|5,-1|6,-1|7,-1|8,-1";
var stack = new Stack<Pair>();
stack.Push(new Pair());
foreach(var x in xs)
if(x == '|')
stack.Push(new UserQuery.Pair());
else
stack.Peek().Accept(x);
foreach (var x in stack.Reverse())
Console.WriteLine(x);
}
sealed class Pair
{
Action<char> _Accept;
readonly List<char> Line = new List<char>();
readonly List<char> Group = new List<char>();
public Pair()
{
_Accept = x => Line.Add(x);
}
public void Accept(char c)
{
if(c == ',')
_Accept = x => Group.Add(x);
else
_Accept(c);
}
public override string ToString()
{
return "Line:" + new string(Line.ToArray()) + " Group:" + new string(Group.ToArray());
}
}

Nested JSON Array C#

I am trying to deserialize a JSON array that has an additional nested object.
Here is a sample C# code. It returns data until it gets to the second array. I know it needs a second foreach loop but I can't seem to get it to work. Any help would be greatly appreciated. Thank you.
string sJSON = #" [{""dateNumeric"":1216000000,""hourOfDay"":0,""customerNumber"":12,""storedepartment"":[{""department"":333,""descriptionOfDepartment"":""Department A""},{""department"":111,""descriptionOfDepartment"":""Department B""}]},{""dateNumeric"":1216000000,""hourOfDay"":3,""customerNumber"":3,""storedepartment"":[{""department"":999,""descriptionOfDepartment"":""Department X""},{""department"":888,""descriptionOfDepartment"":""Department Y""}]}]";
JArray a = JArray.Parse(sJSON);
foreach (JObject o in a.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
string name = p.Name;
string value = (string)p.Value;
Console.WriteLine(name + "-- " + value);
}
}
You can use Newtonsoft.json library for serializing/deserializing the data, as per your requirement kindly follow below code :
First you need to create the class which will capture the data in specified format(as per your data requirement) :
public class RootObject
{
public int dateNumeric { get; set; }
public int hourOfDay { get; set; }
public int customerNumber { get; set; }
public List<Storedepartment> storedepartment { get; set; }
}
public class Storedepartment
{
public int department { get; set; }
public string descriptionOfDepartment { get; set; }
}
Now , for deserialising the Json data use below statement :
string sJSON = #" [{""dateNumeric"":1216000000,""hourOfDay"":0,""customerNumber"":12,""storedepartment"":[{""department"":333,""descriptionOfDepartment"":""Department A""},{""department"":111,""descriptionOfDepartment"":""Department B""}]},{""dateNumeric"":1216000000,""hourOfDay"":3,""customerNumber"":3,""storedepartment"":[{""department"":999,""descriptionOfDepartment"":""Department X""},{""department"":888,""descriptionOfDepartment"":""Department Y""}]}]";
List<RootObject> Data = JsonConvert.DeserializeObject<List<RootObject>>(sJSON);
Once you get data in your list you can perform your required operation on list
Actually you might be able to properly parse your JSON string if you use the following approach.
public static void ProcessJObject(JProperty obj)
{
string name = obj.Name;
string value = "";
if (obj.Value.Type == JTokenType.Array)
{
Console.WriteLine("Array: " + name);
ProcessJArray((JArray)obj.Value);
}
else
{
value = (string)obj.Value;
Console.WriteLine(name + "-- " + value);
}
}
public static void ProcessJArray(JArray arr)
{
foreach (JObject o in arr.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
ProcessJObject(p);
}
}
}
static void Main(string[] args)
{
string sJSON = #" [{""dateNumeric"":1216000000,""hourOfDay"":0,""customerNumber"":12,""storedepartment"":[{""department"":333,""descriptionOfDepartment"":""Department A""},{""department"":111,""descriptionOfDepartment"":""Department B""}]},{""dateNumeric"":1216000000,""hourOfDay"":3,""customerNumber"":3,""storedepartment"":[{""department"":999,""descriptionOfDepartment"":""Department X""},{""department"":888,""descriptionOfDepartment"":""Department Y""}]}]";
JArray a = JArray.Parse(sJSON);
ProcessJArray(a);
Console.Read();
}
So what have I done here. I simply divided the problem of parsing json in two smaller problems one that is solved by the ProcessJObject function (parsing and printing JProperty) and one that is solved by the ProcessJArray function (looping through the JArray and for each JProperty it contain passing it to ProcessJObject function). So now the parsing problem upto any point of nesting of JSON array is solved by the above approach.
Hope it helps.
static void JsonConvert()
{
string sJSON = #"[{""dateNumeric"":1216000000,""hourOfDay"":0,""customerNumber"":12,""storedepartment"":[{""department"":333,""descriptionOfDepartment"":""Department A""},{""department"":111,""descriptionOfDepartment"":""Department B""}]},{""dateNumeric"":1216000000,""hourOfDay"":3,""customerNumber"":3,""storedepartment"":[{""department"":999,""descriptionOfDepartment"":""Department X""},{""department"":888,""descriptionOfDepartment"":""Department Y""}]}]";
var storeDetail = Newtonsoft.Json.JsonConvert.DeserializeObject<List<StoreDetail>>(sJSON);
//iterate your list here
}
public class StoreDetail
{
[JsonProperty("dateNumeric")]
public string DateNumeric { get; set; }
[JsonProperty("hourOfDay")]
public int HourOfDay { get; set; }
[JsonProperty("customerNumber")]
public int CustomerNumber { get; set; }
[JsonProperty("storedepartment")]
public List<StoreDepartment> StoreDepartment { get; set; }
}
public class StoreDepartment
{
[JsonProperty("department")]
public int Department { get; set; }
[JsonProperty("descriptionOfDepartment")]
public string DescriptionOfDepartment { get; set; }
}
string sJSON = #" [{""dateNumeric"":1216000000,""hourOfDay"":0,""customerNumber"":12,""storedepartment"":[{""department"":333,""descriptionOfDepartment"":""Department A""},{""department"":111,""descriptionOfDepartment"":""Department B""}]},{""dateNumeric"":1216000000,""hourOfDay"":3,""customerNumber"":3,""storedepartment"":[{""department"":999,""descriptionOfDepartment"":""Department X""},{""department"":888,""descriptionOfDepartment"":""Department Y""}]}]";
object dJson = Newtonsoft.Json.JsonConvert.DeserializeObject<JArray>(sJSON);
Console.WriteLine(dJson.ToString());
JArray a = JArray.Parse(sJSON);
foreach (JObject o in a.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
if (p.First.Count() == 0)
{
string name = p.Name;
string value = (string)p.Value;
Console.WriteLine(name + "-- " + value);
}
else
{
string name = p.Name;
Console.WriteLine(name);
string subStr = p.Value.ToString();
JArray aSub = JArray.Parse(subStr);
foreach (JObject oSub in aSub.Children<JObject>())
{
foreach (JProperty pSub in oSub.Properties())
{
string nameSub = pSub.Name;
string valueSub = (string)pSub.Value;
Console.WriteLine("\t" + nameSub + "-- " + valueSub);
}
}
}
}
}
Console.ReadLine();

Categories

Resources