void Populate(JsonValue json, RootElement root, JsonValue data)
{
if (json.ContainsKey("title"))
{
root.Caption = json["title"];
}
JsonValue jsonRoot = null;
try {
jsonRoot = json["root"];
} catch (Exception) {
Console.WriteLine("Bad JSON: could not find the root element - " + json.ToString());
return;
}
foreach (JsonObject section in jsonRoot)
{
var sec = new Section(section.s("caption"), section.s("footer"));
if (section.ContainsKey("elements"))
{
foreach (JsonObject elem in section["elements"])
{
var dataForElement = data;
var bindExpression = elem.s("bind");
if (bindExpression != null)
{
try {
if (data != null && data.JsonType == JsonType.Object)
{
var bind = elem.s("bind");
if (data != null && !string.IsNullOrEmpty(bind) && data.ContainsKey(bind))
{
dataForElement = data[bind];
}
}
else if (bindExpression.StartsWith("#"))
{
dataForElement = _controller.GetValue(bindExpression.Replace("#", ""));
}
} catch (Exception) {
Console.WriteLine("Exception when binding element " + elem.ToString());
}
}
_parseElement(elem, sec, dataForElement);
}
}
else if (section.ContainsKey("iterate") && data != null)
{
string iterationname = section["iterate"];
string emptyMessage = section.ContainsKey("empty") ? section["empty"].CleanString() : "Empty";
var iterationdata = string.IsNullOrEmpty(iterationname) ? (JsonArray)data : (JsonArray)data[iterationname];
var template = (JsonObject)section["template"];
var items = iterationdata.ToList();
if (items.Count > 0)
{
foreach (JsonValue v in items)
{
_parseElement(template, sec, v);
}
}
else
{
sec.Add(new EmptyListElement(emptyMessage));
}
}
else if (section.ContainsKey("iterateproperties") && data != null)
{
string iterationname = section["iterateproperties"];
string emptyMessage = section.ContainsKey("empty") ? section["empty"].CleanString() : "Empty";
var iterationdata = string.IsNullOrEmpty(iterationname) ? (JsonObject)data : (JsonObject)data[iterationname];
var template = (JsonObject)section["template"];
var items = iterationdata.Keys;
if (items.Count > 0)
{
foreach (string v in items)
{
var obj = new JsonObject();
obj.Add(v, iterationdata[v]);
_parseElement(template, sec, obj);
}
}
else
{
sec.Add(new EmptyListElement(emptyMessage));
}
}
root.Add(sec);
}
}