I have a JSON file.
{
"time": [
{
"id": "9999",
"name": "Foo",
"subitem": [
{
"name": "Bar",
"id": "99990",
"visible": true,
"subitem": [
{
"id": "999901",
"name": "Flex",
"visible": true
},
{
"name": "Bear",
"id": "999902",
"visible": true
},
{
"name": "James",
"id": "999903",
"visible": true
}
]
},
{
"name": "Smith",
"id": "999966",
"visible": true
},
{
"name": "John",
"id": "999933",
"visible": true
}
],
"visible": true
},
{
"name": "Doe",
"id": "1111",
"visible": true,
"subitem": [
{
"name": "Jack",
"id": "111111",
"visible": true
},
{
"name": "Wilson",
"id": "111188",
"visible": true
},
{
"name": "Andy",
"id": "111144",
"visible": true
},
{
"name": "Gibbs",
"id": "111155",
"visible": true
}
]
}
],
"name": "asdf",
"id": "13",
"visible": true
}
I also have a JObject and a method to get all the JSON data and store it in this object.
json1 = ti.GetTimeItems();
I have 2 methods in another class to write to the JSON file. Where datafolder is the path.
public void WriteToJson(JObject obj)
{
string fileName = dataFolder + "json1.json";
WriteToJson(fileName, obj);
}
private void WriteToJson(string fileName, JObject obj)
{
using (StreamWriter file = File.CreateText(fileName))
using (JsonTextWriter writer = new JsonTextWriter(file))
{
obj.WriteTo(writer);
}
}//end WriteToJson
Then i have a windows form where i want to take the text from 2 textboxes and add these to the JSON file.
Finally i have my click event
private void button1_Click_1(object sender, EventArgs e)
{
//string json = File.ReadAllText(url);
//JArray time = (JArray)json1.SelectToken("time");
json1.Add(new JObject(
new JProperty("name", textBoxName.Text),
new JProperty("id", textBoxId.Text),
new JProperty("visible", true)));
ti.WriteToJson(json1);
}
My problem is that i cannot seem to write to the array "time" in the JObject.
I managed to write to the file but in root instead of inside the array.
I have tried json1.SelectToken("time") and lots of different approaches, like this one http://stackoverflow.com/questions/15413825/how-do-you-add-a-jtoken-to-an-jobject#15782238 and also some approaches from the Newtonsoft documentation.
Any help is appriciated
Problem solved by ((JArray)json1.GetValue("time")). Selecting the array in the JObject json1 and adding to that instead of the root.
Hope this will help someone.
((JArray)json1.GetValue("time")).Add(
new JObject(
new JProperty("name", textBoxName.Text),
new JProperty("id", textBoxId.Text),
new JProperty("visible", true)));
ti.WriteToJson(json1);
Related
I am using the Mailchimp template to send emails through Mandrill. Email being sent successfully. But the variables are not rendering. I tried lots of settings but unfortunately, it is not working. My code is looking like the following.
<p>Dear {{customerName}},</p>
<p>Thank you for using XXXXX to process your return.</p>
<p>All you have to do is bring your parcel along with this e-mail to {{pudoLocation}} at {{emailPudoAddress}}.</p>
And In the Email output, it is showing like this.
And My request JSON to API https://mandrillapp.com/api/1.0/messages/send-template.json is:-
valid json is `{
"key": "xxxxxxxxxxxxxxx",
"template_name": "TestTemplate",
"template_content": [],
"message": {
"subject": "TestEmail",
"from_email": "xxx.xx#xxxxx.in",
"from_name": "Drop2Shop",
"to": [{
"Email": "xxxxx.xxx#xxxxxx.in",
"Name": "Amrit Pannu",
"Type": "to"
}],
"headers": {
"Reply-To": "xxxxx.xxx#xxxx.in"
},
"important": false,
"track_clicks": true,
"track_opens": true,
"merge_language": "handlebars",
"global_merge_vars": [{
"name": "pudoLocation",
"content": "TRK00000028"
},
{
"name": "customerName",
"content": "TRK00000028"
}],
"tags": [""]
}
}`
Please can someone help me here what I missing in this?
Thanks and Advance
You can pass global variables in mandrill using *|VAR1|*. To pass array you can use {{handlebars}}.
The content will be like this:
<p>Dear *|customerName|*,</p>
<p>Thank you for using XXXXX to process your return.</p>
<p>All you have to do is bring your parcel along with this e-mail to *|pudoLocation|* at *|emailPudoAddress|*.</p>
The JSON should be like this only:
{
"key": "XXXXXXXXXXXXXXX",
"template_name": "XXXXXXXXXXXXXXXXXX",
"template_content": [],
"message": {
"subject": "TestEmail",
"from_email": "xxxx#xxxxxxxxxxx.in",
"from_name": "xxxxxx",
"to": [
{
"email": "xxxx#xxxxxxxxxxx.in",
"name": "xxxxx xxxxx",
"type": "to"
}
],
"headers": {
"reply_to": "xxxx.xxxx#xxxx.in"
},
"important": false,
"track_opens": true,
"track_clicks": true,
"merge_language": "handlebars",
"global_merge_vars": [
{
"name": "trackingNumber",
"content": "TRK00000028"
},
{
"name": "customerName",
"content": "Amrit Pannu"
},
{
"name": "eCommerceRetailer",
"content": "Jojo Retailer"
},
{
"name": "goodsDescription",
"content": "Tricycles, Scooters, and Similar Wheeled Toys; Dolls' Carriages"
},
{
"name": "shippingDate",
"content": "2021-07-07"
},
{
"name": "numberOfPackages",
"content": "45"
},
{
"name": "shipFromAddress",
"content": "IRELAND"
},
{
"name": "shipToAddress",
"content": "Britain"
},
{
"Name": "pudoAddress",
"Content": "USA"
},
{
"name": "shipFromContact",
"content": "Commin"
},
{
"name": "shipToContact",
"content": "Stark"
},
{
"name": "customerReference",
"content": "DF7889FSDHCB"
},
{
"name": "pudoLocation",
"content": "Denmark"
},
{
"name": "emailPudoAddress",
"content": "amrit#mailinator.com"
},
{
"name": "unsubscribePageUrl",
"content": ""
},
{
"name": "email",
"content": "amrit#mailinator.com"
},
{
"name": "scanEventTime",
"content": "12:07"
},
{
"name": "scanEventDate",
"content": "07 July 2021"
},
{
"name": "packageItems",
"content": [
{
"GoodsDescription": "869c6f67-f33d-4b30-a274-79b635d12461",
"ReturnReason": "c3b4b071-7664-4060-a39f-52c24147a1ce",
"Quantity": 3,
"Value": 6
},
{
"GoodsDescription": "5e2c625b-74e6-4e90-bb52-6595e9f3d088",
"ReturnReason": "f0949b28-f9a7-406e-8676-b8ce6c714509",
"Quantity": 3,
"Value": 14
},
{
"GoodsDescription": "cffe036a-2441-41af-82e1-130f9169924b",
"ReturnReason": "f31956b9-c24e-492e-b11f-4b4e19489b13",
"Quantity": 1,
"Value": 5
},
{
"GoodsDescription": "f8f64467-6926-4f08-9d4e-aa924dc1af35",
"ReturnReason": "d1f759b0-8e54-4119-94ee-6afe1bc49766",
"Quantity": 4,
"Value": 0
},
{
"GoodsDescription": "496f4e0e-739d-4fce-8a37-85113f27c4d4",
"ReturnReason": "b8d98439-928f-4e6c-bb56-01e6f8fb6be6",
"Quantity": 2,
"Value": 5
},
{
"GoodsDescription": "afe2986c-e51e-4cfe-9506-f9ef2afa5657",
"ReturnReason": "4e6e34f6-d921-46fb-8f4a-b04afd0856a7",
"Quantity": 4,
"Value": 12
},
{
"GoodsDescription": "13ac561a-d161-46a5-9795-8481e99a3afd",
"ReturnReason": "73f4441b-dcff-4f68-a58e-320a29a167c8",
"Quantity": 1,
"Value": 7
},
{
"GoodsDescription": "135e083b-0408-4445-9a0c-3656a46f7eab",
"ReturnReason": "325c7144-8f7d-4712-b708-1702416ca02c",
"Quantity": 2,
"Value": 13
},
{
"GoodsDescription": "ee510bfd-58ea-4707-9c52-26913b190b27",
"ReturnReason": "854629a5-289b-46c9-a072-099e2a572307",
"Quantity": 4,
"Value": 12
},
{
"GoodsDescription": "b6d6fa6e-a327-4014-b019-0c4cd0098da6",
"ReturnReason": "02394799-761c-46f0-af79-d8bc92b2c1b5",
"Quantity": 1,
"Value": 13
}
]
},
{
"name": "currentYear",
"content": 2021
}
],
"tags": null,
"inline_css": true
}
For more information, please see this: https://mailchimp.com/developer/transactional/docs/templates-dynamic-content/#dynamic-content
I'm probably too late, but if it can help someone else.
It's not working because you have to remove all the backslashes Mailchimp added when send it to Mandrill before your variables. Change : \{{customerName}} to {{customerName}}
Note: Im working with System.Text.Json package
Below is JSON I am getting from a database. I have to go through each of the keys in the JSON and check if there is a period (.) in the key name; if so, I need to add a property required with the value of true in the JSON in order to provide runtime validation:
validate:{"required", true}
Here is my JSON:
{
"display": "wizard",
"settings": {},
"components": [{
"title": "Event Information",
"label": "Event Information",
"type": "panel",
"key": "EventInformation",
"components": [{
"label": "Row1Columns",
"columns": [{
"components": [{
"label": "Event Date",
"format": "dd/MM/yyyy hh:mm a",
"tableView": false,
"datePicker": {
"disableWeekends": false,
"disableWeekdays": false
},
"validate": {
"unique": true
},
"key": "Event.EventDate",
"type": "datetime",
"input": true,
"suffix": "<i ref=\"icon\" class=\"fa fa-calendar\" style=\"\"></i>",
"widget": {
"type": "calendar",
"displayInTimezone": "viewer",
"language": "en",
"useLocaleSettings": false,
"allowInput": true,
"mode": "single",
"enableTime": true,
"noCalendar": false,
"format": "dd/MM/yyyy hh:mm a",
"hourIncrement": 1,
"minuteIncrement": 1,
"time_24hr": false,
"minDate": null,
"disableWeekends": false,
"disableWeekdays": false,
"maxDate": null
}
}],
"width": 6,
"offset": 0,
"push": 0,
"pull": 0
}, {
"components": [{
"label": "Duration (minutes)",
"mask": false,
"spellcheck": true,
"tableView": false,
"delimiter": false,
"requireDecimal": false,
"inputFormat": "plain",
"key": "Event.Duration",
"type": "number",
"input": true
}],
"width": 6,
"offset": 0,
"push": 0,
"pull": 0
}],
"tableView": false,
"key": "row1Columns",
"type": "columns",
"input": false
}, {
"label": "Row2Columns",
"columns": [{
"components": [{
"label": "Event Category",
"widget": "choicesjs",
"tableView": true,
"dataSrc": "custom",
"data": {
"custom": "values = getEventCategoryValues()"
},
"valueProperty": "AgencyEventCategoryId",
"template": "<span>{{ item.text }}</span>",
"selectThreshold": 0.3,
"validate": {
"required": true
},
"key": "Event.AgencyEventCategoryId",
"type": "select",
"indexeddb": {
"filter": {}
},
"input": true
}],
"width": 6,
"offset": 0,
"push": 0,
"pull": 0
}, {
"components": [{
"label": "Attendance",
"widget": "choicesjs",
"tableView": true,
"multiple": false,
"dataSrc": "custom",
"data": {
"custom": "values = getAttendanceValues()"
},
"valueProperty": "AgencyEventAttendanceId",
"template": "<span>{{ item.text }}</span>",
"selectThreshold": 0.3,
"validate": {
"required": true,
},
"key": "Event.AgencyEventAttendanceId",
"type": "select",
"indexeddb": {
"filter": {}
},
"input": true
}],
"width": 6,
"offset": 0,
"push": 0,
"pull": 0
}],
"tableView": false,
"key": "row2Columns",
"type": "columns",
"input": false
}, {
"label": "Event Options",
"widget": "choicesjs",
"tableView": true,
"multiple": true,
"dataSrc": "custom",
"data": {
"custom": "values = getEventManagerValues(data.Event.AgencyEventCategoryId)"
},
"template": "<span>{{ item.text }}</span>",
"refreshOn": "Event.AgencyEventCategoryId",
"clearOnRefresh": true,
"selectThreshold": 0.3,
"calculateServer": false,
"validate": {
"required": true,
"multiple": true
},
"key": "Event.EventDetail",
"type": "select",
"indexeddb": {
"filter": {}
},
"input": true
}, {
"label": "Casenote",
"wysiwyg": true,
"autoExpand": true,
"spellcheck": true,
"tableView": true,
"calculateServer": false,
"key": "Event.EventCasenote[0].Casenote",
"type": "textarea",
"input": true
}],
"input": false,
"tableView": false,
"breadcrumbClickable": true,
"buttonSettings": {
"previous": true,
"cancel": true,
"next": true
},
"collapsible": false
}]
}
One of the options would be to parse json into JObject and add property to it via Newtonsoft's Json.NET:
var obj = JObject.Parse("{'key':'value'}");
obj.Add("required", true);
Console.WriteLine(obj); // { "key": "value", "required": true }
To add new object you can use this overload of Add:
obj.Add("validate", JObject.FromObject(new { required = true }));
So the whole solution will look something like this:
var obj = JObect.Parse(your_json);
foreach(var token in obj.DescendantsAndSelf().ToList()) // ToList is important!!!
{
if(token is JObject xObj)
{
// check your conditions for adding property
// check if object does not have "validate" property
if(satisfies_all_conditions)
{
xObj.Add("validate", JObject.FromObject(new { required = true }));
}
}
}
I was having similar issue, and have found a solution, see below the code and comments. I am using Newtonsoft though but it is worth checking if you can use Newtonsoft library and have not found a solution for System.Text.Json.
All controls in your JSON are part of component object/array so we can use JSONPath, see the link for more details.
public void IterateJson(JObject obj, string mandatoryFieldKey)
{
JToken jTokenFoundForMandatoryField = obj.SelectToken
("$..components[?(#.key == '" + mandatoryFieldKey + "')]");
//Now we convert this oken into an object so that we can add properties/objects in it
if (jTokenFoundForMandatoryField is JObject jObjectForMandatoryField)
{
//We check if validate already exists for this field, if it does not
//exists then we add validate and required property inside the if condition
if (jObjectForMandatoryField["validate"] == null)
jObjectForMandatoryField.Add("validate",
JObject.FromObject(new { required = true })); //add validate and required property
else
{
//If validate does not exists then code comes here and
//we convert the validate into a JObject using is JObject statement
if (jObjectForMandatoryField["validate"] is JObject validateObject)
{
//We need to check if required property already exists,
//if it does not exists then we add it inside the if condition.
if (validateObject["required"] == null)
{
validateObject.Add("required", true); //add required property
}
}
}
}
}
It was interesting task for me, so this is what i have written
class Program
{
static void Main(string[] args)
{
string jsonFilePath = #"test.json"; //path to your json
string json = File.ReadAllText(jsonFilePath);
var data = JObject.Parse(json);
CheckJson(data);
Console.ReadLine();
}
static void CheckJson(JToken value)
{
if (value.Values().Count() != 0) //if more than 0 - so value is object or array and we have to call this method for each property
{
foreach (var item in value.Values().ToList())
{
CheckJson(item);
}
}
else if (true) //else - we have exactly value of key, which we can check, for example if . exists or additional checks
{
if (value.Parent.Parent is JObject jObject && jObject["validate"] == null) //check if above "required" property exists
{
jObject.Add("validate", JObject.FromObject(new { required = true })); //add required property
}
}
}
}
This code will add in each object property "required" if it is not exists.
All you need - just add Validation method and call it in if block.
And better to add additional validation that won't continue checking all properties if "required" property exists
I am fetching /me/apprequests from Facebook API. It works and I get the data in JSON format.
Thing is that everything is nested, like a dictionary inside a dictionary.
What i tried:
Dictionary<string, object> dict = Facebook.MiniJSON.Json.Deserialize(result.RawResult) as Dictionary<string, object>;
object data;
string request_code = "";
if (dict.TryGetValue("data", out data))
{
var rc = (((Dictionary<string, object>)data)["id"]);
request_code = (string)rc;
}
Debug.Log("request_code=" + request_code);
I think I need to loop the dictionary to get all id's.
I can confirm that if (dict.TryGetValue("data", out data)) does work correctly and get the dictionary of data arrays, but fails here (((Dictionary<string, object>)data)["id"]); with casting error.
Json looks like:
{
"data": [{
"application": {
"category": "Games",
"link": "https:\/\/www.facebook.com\/games\/?app_id=2523532533",
"name": "game name",
"id": "23432423423"
},
"created_time": "2019-02-27T16:01:15+0000",
"from": {
"name": "David boom",
"id": "387923432423089962"
},
"message": "You are invited",
"to": {
"name": "Dusty Spice",
"id": "10234324421033685"
},
"id": "413880842521239_10156578101000000"
},
{
"application": {
"category": "Games",
"link": "https:\/\/www.facebook.com\/games\/?app_id=2523532533",
"name": "game name",
"id": "23432423423"
},
"created_time": "2019-02-27T14:12:41+0000",
"from": {
"name": "David boom2",
"id": "387923432423089962"
},
"message": "You are invited",
"to": {
"name": "Dusty Spice",
"id": "10234324421033685"
},
"id": "316676422209302_10156578101000000"
}],
"paging": {
"cursors": {
"before": "NDEzODgwODQyNTIxMjM5Ojc1OTQzODY4NAZDZD",
"after": "MzE2Njc2NDIyMjA5MzAyOjc1OTQzODY4NAZDZD"
}
}
}
Managed to make it work if it will help someone:
string request_code = "";
if (dict.TryGetValue("data", out data))
{
int dataLength = ((List<object>)data).Count;
for (int i = 0; i < dataLength; i++)
{
var rc = ((List<object>)data)[i];
var rc2 = (((Dictionary<string, object>)rc)["id"]);
request_code = (string)rc2;
Debug.Log("request_code=" + request_code);
}
}
I have this Joson
{
"Sucess": true,
"Msg": "OK",
"Ret": {
"First": 0,
"Next": true,
"Total": 60,
"Itens": [
{
"ID": 212121,
"Name": "uuuuuuuuuuuuuuuuuuuuuuuu",
"LcID": 9898,
"Oclao": false,
"Lal": {
"ID": 12202,
"Name": "pppppppppppppppppp",
"Pais": "Brasil",
"Dtc": 0.0
},
"Subtipo": {
"ID": 7458,
"Desc": "mnmnmnmnn"
},
"Tipo": {
"Sit": "cor1",
"Sitrm": 0,
"Name": "Shsdfow"
},
"Qtde": 0,
"Qntcoes": 0,
"Pubum": "adfsdfsdfs",
"Evias": {
"arq": {
"Mo": [
"site.com"
],
"Moir": [
"site.com"
]
}
}
},
{
"ID": 9797878,
"Name": "uuuuuuuuuuuuuuuuuuuuuuuu",
"LcID": 9898,
"Oclao": false,
"Lal": {
"ID": 12332,
"Name": "pppppppppppppppppp",
"Pais": "Brasil",
"Dtc": 0.0
},
"Subtipo": {
"ID": 7458,
"Desc": "mnmnmnmnn"
},
"Tipo": {
"Sit": "cor1",
"Sitrm": 0,
"Name": "Shsdfow"
},
"Qtde": 0,
"Qntcoes": 0,
"Pubum": "adfsdfsdfs",
"Evias": {
"arq": {
"Mo": [
"site.com"
],
"Moir": [
"site.com"
]
}
}
}
]
}
}
I would read the array "items" by the field names without using a class to Deserialize, what I did so far was:
JObject jRetorno = JObject.Parse(strJson);
IList<JToken> jItens = jRetorno["Itens"].Children().ToList();
The example http://www.newtonsoft.com/json/help/html/SerializingJSONFragments.htm that uses a class for this, as my json always changes, wanted something like:
strReturn = jItens[1]["ID"];
strReturn = jItens[1]["Name"];
strReturn = jItens[2]["ID"];
strReturn = jItens[2]["Name"];
strReturn = jItens[3]["ID"];
strReturn = jItens[3]["Name"];
Thanks!
You're not that far off. The data you want is one level further down, inside the Ret object. Try it like this:
JObject jRetorno = JObject.Parse(strJson);
IList<JToken> jItens = jRetorno["Ret"]["Itens"].Children().ToList();
foreach (JToken jt in jItens)
{
Console.WriteLine(jt["ID"]);
Console.WriteLine(jt["Name"]);
}
Fiddle: https://dotnetfiddle.net/TwtGyz
I have two json strings I want to compare.
The problem is that when the properties are the same but in a different order.
Simple example:
{
"Number": "123",
"Name": "My name",
"FirstName": "My First name",
"Prop1": false,
"Prop2": [],
"Plans": [],
"SomeList": [
{
"Code": "118",
"Period": {
"From": "2000-01-27T00:00:00.0000000",
"Until": "2003-12-31T00:00:00.0000000"
}
},
{
"Code": "120",
"Period": {
"From": "2004-01-01T00:00:00.0000000",
"Until": "2004-12-31T00:00:00.0000000"
}
}
]
}
and
{
"Number": "123",
"FirstName": "My First name",
"Name": "My name",
"Prop1": false,
"Prop2": [],
"Plans": [],
"SomeList": [
{
"Code": "120",
"Period": {
"From": "2004-01-01T00:00:00.0000000",
"Until": "2004-12-31T00:00:00.0000000"
}
},
{
"Code": "118",
"Period": {
"From": "2000-01-27T00:00:00.0000000",
"Until": "2003-12-31T00:00:00.0000000"
}
}
]
}
These two json's are equal.
The compare function JToken.DeepEquals says it's not equal.
And I don't want to serialize to an object XYZ to compare both jsons.
I want to sort the properties of the json so the JToken.DeepEquals works fine.