I am trying to convert a JSON array to an Object. This is a hacked way but good enough for my purpose.
Basically I am writing a method to get this
var data = [{
"MonthYearShortName": "Sep-13",
"TotalCustomers": 1905.0,
"Aquisition": 317.0,
"Attrition": 9.0
}, {
"MonthYearShortName": "FY-14",
"TotalCustomers": 2158.0,
"Aquisition": 401.0,
"Attrition": 15.0909090909091
}]
into something like this
data = [{
key: 'Attrition',
color: '#d62728',
values: [{
"label": "Sep-13",
"value": 9
}, {
"label": "FY-14",
"value": 15.0909090909091
}]
},
{
key: 'Total Customer',
color: '#1f77b4',
values: [{
"label": "Sep-13",
"value": 1905
}, {
"label": "FY-14",
"value": 2158
}]
},
{
key: 'Aquisition',
color: '#1f7774',
values: [{
"label": "Sep-13",
"value": 317
}, {
"label": "FY-14",
"value": 401
}]
}
];
The colors will be static for now. I will be handling it later.
Now getting to my hacked way of getting this (this is crude I know)
I tried something like this to just get the attrition out
var data = #"[{""MonthYearShortName"": ""Sep-13"",""TotalCustomers"": 1905.0,""Aquisition"": 317.0,""Attrition"": 9.0}, {""MonthYearShortName"": ""FY-14"",""TotalCustomers"": 2158.0,""Aquisition"": 401.0,""Attrition"": 15.0909090909091}]";
JArray a = JArray.Parse(data);
var label1 = a[0]["MonthYearShortName"].ToString();
var label2 = a[1]["MonthYearShortName"].ToString();
var totalCustomer1 = a[0]["TotalCustomers"].ToString();
var totalCustomer2 = a[1]["TotalCustomers"].ToString();
var aquisition1 = a[0]["Aquisition"].ToString();
var aquisition2 = a[1]["Aquisition"].ToString();
var attrition1 = a[0]["Attrition"].ToString();
var attrition2 = a[1]["Attrition"].ToString();
JObject rss1 =
new JObject(
new JProperty("channel",
new JObject(
new JProperty("Key", "Attrition"),
new JProperty("color", "#d62728"),
new JProperty("values",
new JArray(
from p in a
select new JObject(
new JProperty("label", a[0]["MonthYearShortName"].ToString()),
new JProperty("value", attrition1),
new JProperty("label", a[1]["MonthYearShortName"].ToString()),
new JProperty("value", attrition2)))))));
When I tried this I get a
Can not add property label to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.
Now if someone can suggest a cleaner way (as I cant think of any right now), I would be greatful or if my code could be corrected, that would be helpful.
Thanks
Can you try doing it like this?
[Test]
public void Test()
{
var data = #"[
{'MonthYearShortName': 'Sep-13','TotalCustomers': 1905.0,'Aquisition': 317.0,'Attrition': 9.0},
{'MonthYearShortName': 'FY-14','TotalCustomers': 2158.0,'Aquisition': 401.0,'Attrition': 15.0909090909091}
]";
dynamic jarr = JArray.Parse(data);
var attritions = new List<ExpandoObject>();
var aquisitions = new List<ExpandoObject>();
var totalCustomers = new List<ExpandoObject>();
foreach (dynamic o in jarr)
{
dynamic attr = new ExpandoObject();
attr.label = o.MonthYearShortName;
attr.value = o.Attrition;
attritions.Add(attr);
dynamic acq = new ExpandoObject();
acq.label = o.MonthYearShortName;
acq.value = o.Aquisition;
aquisitions.Add(acq);
dynamic cust = new ExpandoObject();
cust.label = o.MonthYearShortName;
cust.value = o.TotalCustomers;
totalCustomers.Add(acq);
}
dynamic attrition = new ExpandoObject();
dynamic aquisition = new ExpandoObject();
dynamic totalCustomer = new ExpandoObject();
attrition.Key = "Attrition";
attrition.Color = "#d62728";
attrition.Values = attritions;
aquisition.Key = "Acquisition";
aquisition.Color = "#1f7774";
aquisition.Values = aquisitions;
totalCustomer.Key = "Total Customer";
totalCustomer.Color = "#1f77b4";
totalCustomer.Values = totalCustomers;
var result = new[] { attrition,totalCustomer, aquisition };
var resultString = JsonConvert.SerializeObject(result, Formatting.Indented);
Console.Write(resultString);
}
Related
I'm reading my json file from and trying to replace the property values. JSON file is below.
{
"fields": {
"summary": "summaryValue",
"project": {
"key": "projectValue"
},
"priority": {
"name": "priorityValue"
},
"Requestor": {
"name": "RequestorValue"
},
"issue": {
"name": "issueValue"
},
"labels": "LabelValue",
"customfield_xyz": "customfield_xyzValue"
}
}
How can I replace the value for each item inside the fields property ?
for ex:
{"fields": {
"summary": "NewsummaryValue",
"project": {
"key": "NewprojectValue"
},
"priority": {
"name": "NewpriorityValue"
}
}
}
Below is the code to parse my json file,
StreamReader r = new StreamReader(filepath);
var jsondata = r.ReadToEnd();
var jobj = JObject.Parse(jsondata);
foreach (var item in jobj.Properties())
{
\\replace code
}
I do not know exactly what you want. But I changed the json information in the code snippet as you wanted.
dynamic dataCollection = JsonConvert.DeserializeObject<dynamic>(jsonData);
string summary = dataCollection["fields"]["summary"];
string project = dataCollection["fields"]["project"]["key"];
string priority = dataCollection["fields"]["priority"]["name"];
dynamic json = new JObject();
json.summary = summary;
json.project = project;
json.priority = priority;
dynamic jsonRoot = new JObject();
jsonRoot.fields = json;
Console.WriteLine(jsonRoot.ToString());
output:
I am having a hard time converting this generic template of facebook to C#. I am not sure if i converted it right. Below is the code i tried but is not rendering on messenger. Thank you.
curl -X POST -H "Content-Type: application/json" -d '{
"recipient":{
"id":"<PSID>"
},
"message":{
"attachment":{
"type":"template",
"payload":{
"template_type":"generic",
"elements":[
{
"title":"Welcome!",
"image_url":"https://petersfancybrownhats.com/company_image.png",
"subtitle":"We have the right hat for everyone.",
"default_action": {
"type": "web_url",
"url": "https://petersfancybrownhats.com/view?item=103",
"webview_height_ratio": "tall",
},
"buttons":[
{
"type":"web_url",
"url":"https://petersfancybrownhats.com",
"title":"View Website"
},{
"type":"postback",
"title":"Start Chatting",
"payload":"DEVELOPER_DEFINED_PAYLOAD"
}
]
}
]
}
}
}
}' "https://graph.facebook.com/v2.6/me/messages?access_token=<PAGE_ACCESS_TOKEN>"
This is what i tried in c# but it is not working. I am not sure if i converted it the proper way. Any help would be appreciated thank you.
Activity previewReply = stepContext.Context.Activity.CreateReply();
previewReply.ChannelData = JObject.FromObject(
new
{
attachment = new
{
type = "template",
payload = new
{
template_type = "generic",
elements = new
{
title = "title",
subtitle = "subtitle",
image_url = "https://thechangreport.com/img/lightning.png",
buttons = new object[]
{
new
{
type = "element_share,",
share_contents = new
{
attachment = new
{
type = "template",
payload = new
{
template_type = "generic",
elements = new
{
title = "x",
subtitle = "xx",
image_url = "https://thechangreport.com/img/lightning.png",
default_action = new
{
type = "web_url",
url = "http://m.me/petershats?ref=invited_by_24601",
},
buttons = new
{
type = "web_url",
url = "http://m.me/petershats?ref=invited_by_24601",
title = "Take Quiz",
},
},
},
},
},
},
},
},
},
},
});
await stepContext.Context.SendActivityAsync(previewReply);
The elements and buttons attributes need to be lists. Take a look at the example template below.
var attachment = new
{
type = "template",
payload = new
{
template_type = "generic",
elements = new []
{
new {
title = "title",
image_url = "https://thechangreport.com/img/lightning.png",
subtitle = "subtitle",
buttons = new object[]
{
new {
type = "element_share",
share_contents = new {
attachment = new {
type = "template",
payload = new
{
template_type = "generic",
elements = new []
{
new {
title = "title 2",
image_url = "https://thechangreport.com/img/lightning.png",
subtitle = "subtitle 2",
buttons = new object[]
{
new {
type = "web_url",
url = "http://m.me/petershats?ref=invited_by_24601",
title = "Take Quiz"
},
},
},
},
},
}
},
},
},
},
},
},
};
reply.ChannelData = JObject.FromObject(new { attachment });
Note, you only need to add a share_contents element to your template if your main template is different from the template you are trying to share. Otherwise, your button can just be new { type = "element_share" }, which makes the template far less complex.
Also, be sure to Whitelist all of your URLs and make sure all of the image URLs work properly - a couple of them weren't working properly. The template won't render if the URLs aren't Whitelisted and image links are broken.
Hope this helps!
just wondering I am using a web method to return some json data to a web form. anyway I don't want the entire class in json just two of the columns. so I used linq to get the columns here is an example.
IEnumerable<Person> model = new List<Person>
{
new Person { id = 1, Name = "Bryan", Phone = "218-0211", Email = "bryan#mail.mil" },
new Person { id = 2, Name = "Joe", Phone = "248-0241", Email = "joe#mail.mil" },
new Person { id = 3, Name = "Fred", Phone = "354-0441", Email = "fred#mail.mil" },
new Person { id = 4, Name = "Mary", Phone = "344-3451", Email = "mary#mail.mil" },
new Person { id = 5, Name = "Jill", Phone = "127-3451", Email = "jill#mail.mil" }
};
var mysubset = from a in model select new { a. Name, a.Email };
unfotunately when I then serialize my result and send it back I lose the column names. so data.name doesn't work so I was wondering can I give names to a var type? for example is there a way to do this?
var mysubset = from a in model select new { a. Name, a.Email };
string myname as string;
foreach (var item in mysubset)
{
myname = subset.Name;
}
ok here is the actual code sorry it is in vb but that is the project I inherited
Dim mycollection = From a in cmpnyList select {a.CmpnyName, a.ShipFrom}
return jsSerialize.Serialize(mycollection)
the json returned from that is
[{"Company A","New York"},{"Company B", "Harrisburg"}]
so I'm trying to get back something like
[{"CmpnyName":"Company A", "ShipFrom": "New York"},
{"CmpnyName": "Company B", "ShipFrom": "Harrisburg}]
I believe you're using json.net the answer would be something like this using jobject(newtonsoft.json.linq)
JObject o = new JObject(
new JProperty("PersonssList",
new JArray(
from p in model
select new JObject(
new JProperty("PersonName", p.Name),
new JProperty("Email", p.Email)))));
and the result would be this json
{
"PersonssList": [
{
"PersonName": "Bryan",
"Email": "bryan#mail.mil"
},
{
"PersonName": "Joe",
"Email": "joe#mail.mil"
},
{
"PersonName": "Fred",
"Email": "fred#mail.mil"
},
{
"PersonName": "Mary",
"Email": "mary#mail.mil"
},
{
"PersonName": "Jill",
"Email": "jill#mail.mil"
}
]
i want to retrieve all contacts based on account in sugarcrm rest api using C# .net
i have tried
json = serializer.Serialize(new
{
session = sessionId,
module_name = "accounts",
query = "",
order_by = "",
offset = "0",
select_fields = "",
link_name_to_fields_array = "",
max_results = "2000",
deleted = 0
});
values = new NameValueCollection();
values["method"] = "get_entry_list";
values["input_type"] = "json";
values["response_type"] = "json";
values["rest_data"] = json;
response = client.UploadValues(sugarUrl, values);
responseString = Encoding.Default.GetString(response);
var accountsList = serializer.Deserialize<Dictionary<string, dynamic>>(responseString);
i am able to get all accounts and contacts but i am not getting relations between them i.e which contact belong to which account
Thanks for help in advance
UPDATE :
object[] linkNameToFieldsArray = new object[1]
{
new object[2, 2]
{
{ "name", "contacts" },
{ "value", new string[2]
{ "id", "last_name"
}
}
};
json = serializer.Serialize(new
{
session = sessionId,
module_name = "accounts",
query = "",
order_by = "",
offset = "0",
select_fields = "",
link_name_to_fields_array = linkNameToFieldsArray , ***//just added this to get related records***
max_results = "2000",
deleted = 0
});
values = new NameValueCollection();
values["method"] = "get_entry_list";
values["input_type"] = "json";
values["response_type"] = "json";
values["rest_data"] = json;
response = client.UploadValues(sugarUrl, values);
responseString = Encoding.Default.GetString(response);
var accountsList = serializer.Deserialize<Dictionary<string, dynamic>>(responseString);
Assuming a SugarCRM 6.4 or 6.5 system and API version REST v4_1...
I don't know the C#/.NET syntax/lingo, but 'link_name_to_fields_array' needs to be an array with keys of module names (e.g. "Contacts") and values that are arrays of the fields you want. The JSON would look like this:
{
"session":"asdfasdfsrf9ebp7jrr71nrth5",
"module_name":"Accounts",
"query":"",
"order_by":null,
"offset":0,
"select_fields":[
"id",
"name"
],
"link_name_to_fields_array":[
{
"name":"contacts",
"value":[
"id",
"last_name"
]
}
],
"max_results":"2",
"deleted":false
}
Also - I wrote this to help non PHP-devs interact with this version of the API, since documention is largely PHP based. You may find it useful: https://gist.github.com/matthewpoer/b9366ca4197a521a600f
I have my JSON in a string. How can I use JavascriptSerializer to deserialize it and find the value of SSOID?
{
"Addresses": [
{
"Address": "123 Test Road",
"State": "Mississippi"
}
],
"Birthdate": "April 12 2012",
"CreateDate": "April 13 2012",
"IDs": [
{
"isDefault": false,
"PurchaseID": "883"
}
],
"Sex": "Male",
"SSOID": 23444,
"Suffix": null,
"BoardID": 4324
}
In this particular case:
string s = "your json string";
System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
var obj = js.DeserializeObject(s) as Dictionary<string,object>;
int ssoid = (int)obj["SSOID"];
var js = new JavaScriptSerializer();
var deserialized = (Dictionary<string, object>) js.DeserializeObject(json);
var ssoid = (int) deserialized["SSOID"];
var SSOID = new JavaScriptSerializer()
.Deserialize<Dictionary<string, object>>(json)["SSOID"];
OR
dynamic jObj = new JavaScriptSerializer().DeserializeObject(json);
var SSOID = jObj["SSOID"];