Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Thursday, September 3, 2015 4:01 PM | 1 vote
I have a template of values and I want to create a Json object that contains keys and values. The json will look like
"global_merge_vars": [
{ "name": "timeCreated",
"content": "01/02/0001 04:01:51"
},
{ "name": "Car model",
"content": "Audio A6"
}
etc
this is my code
public static void send(IDictionary<string, string> templateContent)
{
Newtonsoft.Json.Linq.JObject r = new Newtonsoft.Json.Linq.JObject();
try
{
// Template variables
Newtonsoft.Json.Linq.JArray content = new Newtonsoft.Json.Linq.JArray();
foreach (string key in templateContent.Keys)
{
// We have prefixed variables that don't go into template context
if (key.StartsWith("_", StringComparison.Ordinal))
{
continue;
}
string contentItem;
Newtonsoft.Json.Linq.JObject item = new Newtonsoft.Json.Linq.JObject();
item.Add("name", key);
item.Add("content", templateContent.TryGetValue(key, out contentItem));
}
}
catch (Newtonsoft.Json.JsonException e)
{
}
try
{
}
catch (Exception e)
{
}
}
The problem is when I use the "TryGetValue" it return a bool but I need to inset the value of contentItem into "item" so that it look like the json above and not like,
{ "name": "timeCreated", "content": true}
This is a windows phone 8.1 Silverlight app.
All replies (3)
Thursday, September 3, 2015 8:28 PM âś…Answered
You could also do this in one line
item.Add("content", templateContent.TryGetValue(key, out contentItem) ? contentItem : "");
This way if TryGetValue returns true, the value of output paramenter "contentItem" will be added as value of key. Otherwise, empty string will be added.
Dan Randolph - My Code Samples List
Thursday, September 3, 2015 4:14 PM
The TryGetValue() returns a bool indicating whether the value exists or not, and returns the actual value - if exists - in the 'out' parameter. All methods of the form Try... tend to follow this pattern.
You are using the return value of this call rather than the 'out' argument to set your item value
Try something like:
if (TryGetValue(key, out contentItem))
{
item.Add("content", contentItem);
}
else
{
// key doesn't exist in dictionary - default value?
item.Add("content", "");
}
Friday, September 4, 2015 7:56 AM
Thanks guys for your help, both answers work good, but I will use Dan's.