Add days to timestamp - c#

I need to add one day to unix timestamp. I got timestamp from API: unixDate = (string)result["dt"]; , result: 1617789600. But now I need to add one day to it. How can I do it?
public static List<Tuple<string, string, string, string>> euDataDaily(string url)
{
var aTuple = new List<Tuple<string, string, string, string>> { };
WebClient c = new WebClient();
var data = c.DownloadString(url);
JObject o = JObject.Parse(data);
string conditionCode="";
string unixDate = "";
string dayTemp="";
foreach (var result in o["daily"])
{
unixDate = (string)result["dt"];
dayTemp = (string)result["temp"]["day"];
foreach (var resultas in result["weather"])
{
conditionCode = (string)resultas["icon"];
}
}
List<Tuple<string, string>> icon = convertIcon(conditionCode);
foreach (var tuple in icon)
{
aTuple.Add(Tuple.Create(dayTemp, tuple.Item1, tuple.Item2, unixDate));
}
return aTuple;
}
JSON example:
{
"daily": [
{
"dt": 1595268000,
"sunrise": 1608124431,
"sunset": 1608160224,
"temp": {
"day": 278.14,
"min": 273.15,
"max": 279.4,
"night": 273.15,
"eve": 275.82,
"morn": 275.35
},
"weather": {
"clouds": 60,
"pop": 0.84,
"uvi": 2.41,
"icon": "cloudy.gif"
}
}
]
}
Thanks for your help!

Since you're already using JObject, you can cast it to an int instead of a string. If you swap out unixDate = (string)result["dt"]; for unixDate = (int)result["dt"];, you'll have the same number but in a int instead of a string. Then you can just add 86400(a day in seconds) and convert it back to a string with ToString().
Do note that, (int) cast does not work for normal strings, it's specific to JObject. If you try to do this on a normal string you'll get InvalidCastException. For normal strings go for int.Parse(or int.TryParse) instead.

Related

Trying to generate custom JSON with anonymous types

I've recently been learning how to generate json and geojson streams from datatables. It's been an uphill battle to say the least.
Currently I'm trying to create a custom JSON stream for a chart. This is the correct JSON format:
{
"labels": ["January","February","March","April"],
"datasets":
[{
"label": "NAME",
"data": [1,2,3,4]
},{
"label": "NUM",
"data": [11,12,13,14]
}]
}
My datatable looks like this:
monthname Data1 Data2
January 1 11
February 2 12
March 3 13
April 4 14
So far this is what I have:
public static string DataTableToCustomJSONString(DataTable dataTable)
{
string monthName = string.Empty;
string data1 = string.Empty;
string data2 = string.Empty;
foreach (DataRow row in dataTable.Rows)
{
monthName += row["MonthName"].ToString() + ",";
data1 += row["data1"].ToString() + ",";
data2 += row["data2"].ToString() + ",";
}
monthName = monthName.Remove(monthName.Length - 1);
data1 = data1.Remove(data1.Length - 1);
data2 = data2.Remove(data2.Length - 1);
var obj = new
{
labels = monthName,
datasets = new dynamic [] {
new { label = "NAME", Data = data1 }
,
new { label = "NUM", Data = data2 },
}
};
return JsonConvert.SerializeObject(obj, Formatting.Indented);
}
Which returns the following json:
{
"labels": "January,February,March,April",
"datasets": [
{
"label": "NAME",
"data": "1,2,3,4"
},
{
"label": "NUM",
"data": "11,12,13,14"
}
]
}
As you can see, the months should be enclosed by brackets and each month has double-quotes (["January","February","March","April"] instead of "January,February,March,April").
Also, the data property should look like this [2,3,4,5], but instead is enclosed by double-quotes (`"11,12,13,14"``).
Also, I'm not sure if iterating through the datatable is the best way to generate the months string.
Any help is appreciated.
When you do this:
monthName += row["MonthName"].ToString() + ",";
You are telling it to concatenate the value into one long string with commas in between. So that's exactly what it's doing for you.
If you want it to be an array, you can use a List<string> and add each value. They will be serialized into a JSON array:
var months = new List<string>();
var data1 = new List<string>();
var data2 = new List<string>();
foreach (DataRow row in dataTable.Rows)
{
months.Add(row["MonthName"].ToString());
data1.Add(row["data1"].ToString());
data2.Add(row["data2"].ToString());
}
Then you also don't need those lines that remove the last comma.

Parsing JSON with fastJson in C#

I could not find an answer in the existing threads for my problem. I have this JSON string:
{
"Count": 4,
"Result:000": {
"Score": 4.571,
"W0DateTime": "2014-08-28 23:00:00",
"W0Value": 1.0164,
"W0Fibonacci": 0,
"Direction": "SHORT",
"StartDate": "2014-08-29 16:30:00",
"EndDate": "2014-08-28 01:00:00",
"BarsCalculated": 80
}
}
How do I get the content of Result:000?
I have this code:
...
public Dictionary<string, object> dictionaryObject;
public void jsonInitStructure(string sJsonString)
{
dictionaryObject = (Dictionary<string , object>) fastJSON.JSON.Parse(sJsonString);
}
...
Count is easy: Convert.ToInt32(dictionaryObject ["Count"]) but how do I get the values from Result:000? For example (Score, StartDate, EndDate, ...)
Have you tried casting it?
var result000 = (Dictionary<string, object>)dictionaryObject["Result:000"];
var result000Score = Convert.ToDouble(result000["Score"]);
Plese have a try...
Array objList = (Array)dictionaryObject["Result:000"] ;
foreach (object obj in objList)
{
Dictionary<string, object> dictionary = new Dictionary<string, object>();
dictionary = (Dictionary<string, object>)obj;
var var1 = dictionary["Score"].ToString();
var var2 = dictionary["W0DateTime"].ToString();
}

Parse dynamic json as simple as possible

I am not much of a C# Programmer so I am fairly new to this, I would like to parse the sample JSON below, I have been using the code:
WebClient client = new WebClient();
string getString = client.DownloadString(url);
dynamic j = JsonConvert.DeserializeObject(getString);
var k = j.rgDescriptions;
dynamic m = JsonConvert.DeserializeObject(k);
foreach (var c in m.descriptions)
{
Console.WriteLine(c);
}
I get error in deserialize of k, I am not sure if I am at the right path though. How do I get the "classid" w/o getting the value of their parent, because it is dynamic and not named, it is a Unique ID.
{
"success": true,
"rgDescriptions": {
"671219543": {
"id": "671219543",
"classid": "253033065",
"instanceid": "93973071",
"amount": "1",
"pos": 274
},
"707030894": {
"id": "707030894",
"classid": "166354998",
"instanceid": "0",
"amount": "1",
"pos": 277
},
Update:
I used this code:
WebClient client = new WebClient();
string getString = client.DownloadString(url);
var jo = JObject.Parse(getString);
var data = (JObject)jo["rgDescriptions"];
foreach (var item in data)
{
Console.WriteLine("{0}: {1}", item.Key, item.Value);
}
I could get what I wanted now, but I need to parse each value. Is there a better way?
You could use JSON.NET and JSONPath to query the incoming JSON, examples here and here
The code below extracts every classid for each object in rgDescriptions
//...
WebClient client = new WebClient();
string getString = client.DownloadString(url);
var obj = JObject.Parse(getString);
var classIds = obj.SelectTokens("$.rgDescriptions.*.classid").Select(x => x.Value<string>()).ToList(); //[253033065,166354998]
//Class ID Where...
var idToSearch = "671219543";
var classId = obj.SelectToken("$.rgDescriptions['" + idToSearch + "']..classid").Value<string>();
//...

return array of arrays instead of array of objects with json.net

I need to return an array of arrays instead of an array of objects for a flot chart.
I can get the following:
data = [{"2012-10": 4140},{"2012-11": 10815},{"2012-12": 10444}];
but need (UPDATE fixed following line):
data = [["2012-10", 4140],["2012-11", 10815],["2012-12", 10444]];
Here is the c# which is parsing inbound json from another source:
public async Task<ActionResult> Chart(string custid)
{
//Get the financial results from DRT
var response = await DominoJSON.getJSON(custid, "drtHistory", "DRT");
JArray UOVol = new JArray();
var array = JArray.Parse(response);
foreach (var token in array)
{
JObject o = JObject.Parse(token.ToString());
int uovol = Convert.ToInt32(o["UOVol"]);
string uodate = o.SelectToken("DATE").ToString();
JObject UOItem = new JObject(new JProperty(uodate, uovol));
UOVol.Add(UOItem);
}
string resultUO = UOVol.ToString();
ViewBag.UOData = resultUO;
return View();
}
And the inbound json being parsed:
[
{
"DATE":"2012-10",
"UOVol":4140,
"FIRev":180,
"AFRev":692.75,
"ABRev":2900,
"OWRev":3791.25,
},
{
"DATE":"2012-11",
"UOVol":10815,
"FIRev":60,
"AFRev":170,
"ABRev":0,
"OWRev":3037.5,
},
{
"DATE":"2012-12",
"UOVol":10444,
"FIRev":40,
"AFRev":514.25,
"ABRev":1450,
"OWRev":7500,
}
]
I can't figure out how to turn the JObjects to arrays. I have tried this with other approaches including using a dictionary and list. Any help or alternate solutions would be helpful. Using VS2013, mvc 5 and EF 6.
Try this:
class Program
{
static void Main(string[] args)
{
string jsonIn = #"
[
{
""DATE"": ""2012-10"",
""UOVol"": 4140,
""FIRev"": 180,
""AFRev"": 692.75,
""ABRev"": 2900,
""OWRev"": 3791.25
},
{
""DATE"": ""2012-11"",
""UOVol"": 10815,
""FIRev"": 60,
""AFRev"": 170,
""ABRev"": 0,
""OWRev"": 3037.5
},
{
""DATE"": ""2012-12"",
""UOVol"": 10444,
""FIRev"": 40,
""AFRev"": 514.25,
""ABRev"": 1450,
""OWRev"": 7500
}
]";
JArray arrayIn = JArray.Parse(jsonIn);
JArray arrayOut = new JArray();
foreach (JObject jo in arrayIn.Children<JObject>())
{
JArray ja = new JArray();
ja.Add(jo["DATE"]);
ja.Add(jo["UOVol"]);
arrayOut.Add(ja);
}
string jsonOut = arrayOut.ToString(Formatting.None);
Console.WriteLine(jsonOut);
}
}
Output:
[["2012-10",4140],["2012-11",10815],["2012-12",10444]]

Convert Newtonsoft.Json.Linq.JArray to a list of specific object type

I have the following variable of type {Newtonsoft.Json.Linq.JArray}.
properties["Value"] {[
{
"Name": "Username",
"Selected": true
},
{
"Name": "Password",
"Selected": true
}
]}
What I want to accomplish is to convert this to List<SelectableEnumItem> where SelectableEnumItem is the following type:
public class SelectableEnumItem
{
public string Name { get; set; }
public bool Selected { get; set; }
}
I am rather new to programming and I am not sure whether this is possible. Any help with working example will be greatly appreciated.
Just call array.ToObject<List<SelectableEnumItem>>() method. It will return what you need.
Documentation: Convert JSON to a Type
The example in the question is a simpler case where the property names matched exactly in json and in code. If the property names do not exactly match, e.g. property in json is "first_name": "Mark" and the property in code is FirstName then use the Select method as follows
List<SelectableEnumItem> items = ((JArray)array).Select(x => new SelectableEnumItem
{
FirstName = (string)x["first_name"],
Selected = (bool)x["selected"]
}).ToList();
The API return value in my case as shown here:
{
"pageIndex": 1,
"pageSize": 10,
"totalCount": 1,
"totalPageCount": 1,
"items": [
{
"firstName": "Stephen",
"otherNames": "Ebichondo",
"phoneNumber": "+254721250736",
"gender": 0,
"clientStatus": 0,
"dateOfBirth": "1979-08-16T00:00:00",
"nationalID": "21734397",
"emailAddress": "sebichondo#gmail.com",
"id": 1,
"addedDate": "2018-02-02T00:00:00",
"modifiedDate": "2018-02-02T00:00:00"
}
],
"hasPreviousPage": false,
"hasNextPage": false
}
The conversion of the items array to list of clients was handled as shown here:
if (responseMessage.IsSuccessStatusCode)
{
var responseData = responseMessage.Content.ReadAsStringAsync().Result;
JObject result = JObject.Parse(responseData);
var clientarray = result["items"].Value<JArray>();
List<Client> clients = clientarray.ToObject<List<Client>>();
return View(clients);
}
I can think of different method to achieve the same
IList<SelectableEnumItem> result= array;
or (i had some situation that this one didn't work well)
var result = (List<SelectableEnumItem>) array;
or use linq extension
var result = array.CastTo<List<SelectableEnumItem>>();
or
var result= array.Select(x=> x).ToArray<SelectableEnumItem>();
or more explictly
var result= array.Select(x=> new SelectableEnumItem{FirstName= x.Name, Selected = bool.Parse(x.selected) });
please pay attention in above solution I used dynamic Object
I can think of some more solutions that are combinations of above solutions. but I think it covers almost all available methods out there.
Myself I use the first one
using Newtonsoft.Json.Linq;
using System.Linq;
using System.IO;
using System.Collections.Generic;
public List<string> GetJsonValues(string filePath, string propertyName)
{
List<string> values = new List<string>();
string read = string.Empty;
using (StreamReader r = new StreamReader(filePath))
{
var json = r.ReadToEnd();
var jObj = JObject.Parse(json);
foreach (var j in jObj.Properties())
{
if (j.Name.Equals(propertyName))
{
var value = jObj[j.Name] as JArray;
return values = value.ToObject<List<string>>();
}
}
return values;
}
}
Use IList to get the JArray Count and Use Loop to Convert into List
var array = result["items"].Value<JArray>();
IList collection = (IList)array;
var list = new List<string>();
for (int i = 0; i < collection.Count; j++)
{
list.Add(collection[i].ToString());
}

Categories

Resources