I have the below object structure present in text file how do I have read this and assign to a list.
"ID": 1,
"PatientNumber": "12",
"Honorific": "Mrs.",
"FirstName": "Abc",
"DisplayName": "Abc",
"Gender": "Female",
"DateOfBirth": 41881,
"Age": 0
"ID": 2,
"PatientNumber": "123",
"Honorific": "Mrs.",
"FirstName": "xyz",
"LastName": "xyz",
"DisplayName": "xyz",
"Gender": "Female",
"DateOfBirth": 41881,
"Age": 0
I tried using split "," but was not able to get value of each property
Since you tagged C#, ASP.NET and .NET, I assume you want to set this data to a Class and append it to a List.
If you're sure that data is not a JSON array then you can use the following code:
var data = File.ReadAllText("PATH_TO_FILE");
var stringDataArr = data.Split("\r\n\r\n");
List<DataObject> dataObjects = new List<DataObject>();
foreach (var stringData in stringDataArr)
{
var dataObject = new DataObject();
foreach (var propValues in stringData.Split(",\r\n"))
{
var prop = propValues.Split(":")[0].Trim('"').Trim();
var value = propValues.Split(":")[1].Trim().Trim('"');
var x = dataObject.GetType().GetProperties();
foreach (var objectProp in dataObject.GetType().GetProperties())
{
if (objectProp.Name == prop)
{
if(objectProp.PropertyType == typeof(int))
{
objectProp.SetValue(dataObject, int.Parse(value));
}
else
{
objectProp.SetValue(dataObject, value);
}
}
}
}
dataObjects.Add(dataObject);
}
public class DataObject
{
public int ID { get; set; }
public string PatientNumber { get; set; }
public string Honorific { get; set; }
public string FirstName { get; set; }
public string DisplayName { get; set; }
public string Gender { get; set; }
public int DateOfBirth { get; set; }
public int Age { get; set; }
}
This is not a best practice. It's written for your data. It probably won't work with different data.
I am trying to generate the HMAC signature. This is for a validation with credit card company. Below is my code to generate the HMAC signature:
public string APISecurityKey(Identity postParameters)
{
String secretAccessKey = "secretkey";
string data = "message";
byte[] secretKey = Encoding.UTF8.GetBytes(secretAccessKey);
HMACSHA256 hmac = new HMACSHA256(secretKey);
hmac.Initialize();
byte[] bytes = Encoding.UTF8.GetBytes(data);
byte[] rawHmac = hmac.ComputeHash(bytes);
return Convert.ToBase64String(rawHmac);
}
They are asking me to substitute the message field with the JSON request (JSON supplied should have all carriage return newline sequences replaced with a space character). My object looks like so:
public class Identity
{
public List<Header> header { get; set; }
public string firstName { get; set; }
public string LastName { get; set; }
public string middleName { get; set; }
public string address { get; set; }
public string mothersName { get; set; }
public string DriversLic { get; set; }
public DateTime insertTime { get; set; }
public string Status { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zip { get; set; }
public DateTime UpdatedOn { get; set; }
}
}
public class Header
{
public string tenantId { get; set; }
public string requestType { get; set; }
public string clientReferenceId { get; set; }
public string expRequestId { get; set; }
public string txnId { get; set; }
public string messageTime { get; set; }
public string options { get; set; }
}
The example given to me for the message is like this:
{"tenantId": "TENANT1","request Type": "Simulator","clientRefere
nceId": "Hunter + ProveID","expRequestId": "333","messageTim
e": "2016-08-04T22:13:07Z","options": {"workflow": "wf1","model
Type":"mt1","responseType":1,"Responses": {…}}}
I am not sure how to include tenantId, tenantId, expRequestId, options as part of my JSON message. I am very new to JSON. I have this partial code:
public static async Task createJSON( Identity postParameters)
{
var tmpRequest = new HttpRequestMessage();
tmpRequest.Content = new StringContent(JsonConvert.SerializeObject(postParameters));
tmpRequest.Content.Headers.Add("tenantId", "V123456");
tmpRequest.Content.Headers.Add("requestType", "PreciseIdOnly");
}
postParameters is my Identity object with values. How can I create that JSON that includes tenantId, tenantId, expRequestId and the object so that I can put that JSON value in the message of APISecurityKey method. Below is the test JSON file that I need to create:
{
"header": {
"tenantId": "V123456",
"requestType": "Precise",
"clientReferenceId": "11111111",
"RequestId": "",
"txnId": "",
"messageTime": "2020-05-28T00:00:02Z",
"options": {}
},
"payload": {
"control": [
{
"option": "SUBSCRIBER_PREAMBLE",
"value": "wer"
},
{
"option": "SUBSCRIBER_OPERATOR_INITIAL",
"value": "WS"
},
{
"option": "SUBSCRIBER_SUB_CODE",
"value": "1111111"
},
{
"option": "PID_USERNAME",
"value": "demo"
},
{
"option": "PID_PASSWORD",
"value": "password"
},
{
"option": "PRODUCT_OPTION",
"value": "11"
}
],
"contacts": [{
"id": "APPLICANT_CONTACT_ID_1",
"person": {
"typeOfPerson": "",
"personIdentifier": "",
"personDetails": {
"dateOfBirth": "1990-12-11",
"yearOfBirth": "",
"age": "",
"gender": "",
"noOfDependents": "",
"occupancyStatus": "",
"mothersMaidenName": "",
"spouseName": ""
},
"names": [{
"id": "",
"firstName": "Test1",
"middleNames": "D",
"surName": "Test2",
"nameSuffix": ""
}]
},
"addresses": [{
"id": "Main_Contact_Address_0",
"addressType": "CURRENT",
"poBoxNumber": "",
"street": "2312 Test Drve",
"street2": "",
"postTown": "test",
"postal": "49548",
"stateProvinceCode": "CA"
}],
"identityDocuments": [{
"documentNumber": "123456789",
"hashedDocumentNumber": "",
"documentType": "SSN"
}]
}]
}
}
I want to generate the same JSOn as the sample above in C# using the objects.
any help will be highly appreciated.
If you using Visual studio, you can create the JSON by going to Edit menu and paster JSON as class. This will create all the classes for you and then you can assign values to the classes by instantiating them
I'm completely new to JSON and need to be able to get a my JSON string converted into a DataTable.
Here is my JSON. I have changed about data for security reasons
[
{
"uuid": "af9fcfc7-61af-4484-aaa8-7dhcced2f2f79",
"call_start_time": 1551892096171,
"call_duration": 1150,
"created_on": "2019-03-06",
"cost": 0,
"call_type": "inbound",
"from": {
"uuid": "",
"type": "number",
"name": "",
"nickname": "",
"number": "+44 7*** ******"
},
"to": {
"uuid": "",
"type": "number",
"name": "",
"nickname": "",
"number": "+44 **** ******0"
},
"answered": true,
"answered_by": {
"uuid": "48bj949-e72e-4239-a337-e181a1b45841",
"type": "sipuser",
"name": "SipUser",
"nickname": "Myself",
"number": "1001"
},
"has_recording": true,
"call_route": "c30e45g0e-3da4-4a67-9a04-27e1d9d31129",
"is_fax": false
},
{
"uuid": "f62kmop2b-f929-4afc-8c05-a8c1bc43225d",
"call_start_time": 1551890795202,
"call_duration": 12,
"created_on": "2019-03-06",
"cost": 0.012,
"call_type": "outbound",
"from": {
"uuid": "68a50328-f5b0-4c5e-837c-667ea50878f3",
"type": "sipuser",
"name": "Spare",
"nickname": "Spare",
"number": "1011"
},
"to": {
"uuid": "",
"type": "number",
"name": "",
"nickname": "",
"number": "+44 *** *** ****"
},
"answered": true,
"answered_by": {
"uuid": "",
"type": "number",
"name": "",
"nickname": "",
"number": "+44 ***1*****0"
},
"has_recording": false,
"call_route": "",
"is_fax": false
},
{
"uuid": "b1b495c4-ecf6-44c0-8020-28c9eddc7afe",
"call_start_time": 1551890780607,
"call_duration": 10,
"created_on": "2019-03-06",
"cost": 0.012,
"call_type": "outbound",
"from": {
"uuid": "68a50328-f5b0-4c5e-837c-667ea50878f3",
"type": "sipuser",
"name": "Spare",
"nickname": "Spare",
"number": "1011"
},
"to": {
"uuid": "",
"type": "number",
"name": "",
"nickname": "",
"number": "+44 *** *** ****"
},
"answered": true,
"answered_by": {
"uuid": "",
"type": "number",
"name": "",
"nickname": "",
"number": "+44 *** *** ****"
},
"has_recording": false,
"call_route": "",
"is_fax": false
}
]
The way I want it presented needs to be similar to the way this website presents the datatable
https://konklone.io/json/
I've been all of the web now and am starting to run out of options. I did try looking into creating it with classes however that wasn't successful.
I have also tried all of the following examples (plus others)
https://www.code-sample.com/2017/04/convert-json-to-datatable-asp-net-c.html
Import Complex JSON file to C# dataTable
Convert JSON to DataTable
https://www.codeproject.com/Questions/590838/convertplusJSONplusstringplustoplusdatatable
Even if this goes into a DataSet and then I sort out the tables from there. Any help at all will be much appreciated.
Edit
I will explain why this is a little bit different from the assumed duplicate question located here
Convert JSON to DataTable
The answer to this question doesn't seem to be taking into account that I have nested JSON's that I need to get access to. I have tried it and I still do not get any of the from/number fields and the to/number fields.
I will admit that my question is a extention to this other duplicate question
Ok so here is the code to parse your JSON structure into a C# List. Once you have this list, you can convert it to a DataTable using the methods that you have researched. I have created a sample Data Table based on your JSON structure.
Your model would be:
public class JsonInfo
{
public string uuid { get; set; }
public string call_start_time { get; set; }
public string call_duration { get; set; }
public string created_on { get; set; }
public string cost { get; set; }
public string call_type { get; set; }
public string answered { get; set; }
public string has_recording { get; set; }
public string call_route { get; set; }
public string is_fax { get; set; }
public From from { get; set; }
public To to { get; set; }
public AnsweredBy answered_by { get; set; }
}
public class From
{
public string uuid { get; set; }
public string type { get; set; }
public string name { get; set; }
public string nickname { get; set; }
public string number { get; set; }
}
public class To
{
public string uuid { get; set; }
public string type { get; set; }
public string name { get; set; }
public string nickname { get; set; }
public string number { get; set; }
}
public class AnsweredBy
{
public string uuid { get; set; }
public string type { get; set; }
public string name { get; set; }
public string nickname { get; set; }
public string number { get; set; }
}
//Create a model to show your information
public class DisplayJsonInfo
{
public string uuid { get; set; }
public string call_start_time { get; set; }
public string call_duration { get; set; }
public string created_on { get; set; }
public string cost { get; set; }
public string from_uuid { get; set; }
public string from_type { get; set; }
public string from_name { get; set; }
public string from_nickname { get; set; }
}
To serialize your JSON into created Model and then create your DataTable:
var json = "[{\"uuid\":\"af9fcfc7-61af-4484-aaa8-7dhcced2f2f79\",\"call_start_time\":1551892096171,\"call_duration\":1150,\"created_on\":\"2019-03-06\",\"cost\":0,\"call_type\":\"inbound\",\"from\":{\"uuid\":\"\",\"type\":\"number\",\"name\":\"\",\"nickname\":\"\",\"number\":\"+44 7*** ******\"},\"to\":{\"uuid\":\"\",\"type\":\"number\",\"name\":\"\",\"nickname\":\"\",\"number\":\"+44 **** ******0\"},\"answered\":true,\"answered_by\":{\"uuid\":\"48bj949-e72e-4239-a337-e181a1b45841\",\"type\":\"sipuser\",\"name\":\"SipUser\",\"nickname\":\"Myself\",\"number\":\"1001\"},\"has_recording\":true,\"call_route\":\"c30e45g0e-3da4-4a67-9a04-27e1d9d31129\",\"is_fax\":false},{\"uuid\":\"f62kmop2b-f929-4afc-8c05-a8c1bc43225d\",\"call_start_time\":1551890795202,\"call_duration\":12,\"created_on\":\"2019-03-06\",\"cost\":0.012,\"call_type\":\"outbound\",\"from\":{\"uuid\":\"68a50328-f5b0-4c5e-837c-667ea50878f3\",\"type\":\"sipuser\",\"name\":\"Spare\",\"nickname\":\"Spare\",\"number\":\"1011\"},\"to\":{\"uuid\":\"\",\"type\":\"number\",\"name\":\"\",\"nickname\":\"\",\"number\":\"+44 *** *** ****\"},\"answered\":true,\"answered_by\":{\"uuid\":\"\",\"type\":\"number\",\"name\":\"\",\"nickname\":\"\",\"number\":\"+44 ***1*****0\"},\"has_recording\":false,\"call_route\":\"\",\"is_fax\":false},{\"uuid\":\"b1b495c4-ecf6-44c0-8020-28c9eddc7afe\",\"call_start_time\":1551890780607,\"call_duration\":10,\"created_on\":\"2019-03-06\",\"cost\":0.012,\"call_type\":\"outbound\",\"from\":{\"uuid\":\"68a50328-f5b0-4c5e-837c-667ea50878f3\",\"type\":\"sipuser\",\"name\":\"Spare\",\"nickname\":\"Spare\",\"number\":\"1011\"},\"to\":{\"uuid\":\"\",\"type\":\"number\",\"name\":\"\",\"nickname\":\"\",\"number\":\"+44 *** *** ****\"},\"answered\":true,\"answered_by\":{\"uuid\":\"\",\"type\":\"number\",\"name\":\"\",\"nickname\":\"\",\"number\":\"+44 *** *** ****\"},\"has_recording\":false,\"call_route\":\"\",\"is_fax\":false}]";
var data = JsonConvert.DeserializeObject<List<JsonInfo>>(json);
//Call your helper method to convert
CreateDataTable cl = new CreateDataTable();
DataTable dt = new DataTable();
DisplayJsonInfo show = new DisplayJsonInfo();
List<DisplayJsonInfo> showInfo = new List<DisplayJsonInfo>();
foreach(var value in data)
{
showInfo.Add(new DisplayJsonInfo
{
call_duration = value.call_duration,
call_start_time = value.call_start_time,
cost = value.cost,
uuid = value.uuid,
created_on = value.created_on,
from_uuid = value.from.uuid,
from_name = value.from.name,
from_type = value.from.type,
from_nickname=value.from.nickname
});
}
dt = cl.ToDataTable(showInfo);
Once you have this use a helper extension like ToDataTable() as mentioned here: Convert JSON to DataTable
Edit:
So after parsing out the information and using this helper to convert your List to DataTable:
using System;
using System.Text;
using System.IO;
using System.Configuration;
using System.Data;
using System.Collections.Generic;
using System.ComponentModel;
public class CreateDataTable
{
public DataTable ToDataTable<T>(IList<T> data)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
}
Your DataTable would look something like this:
Edit Description:
I have created a model only to show your required data into the DataTable. Since I have parsed the JSON data into my C# list, I can access the data shown in my code using foreach loop. Then I simply get the data what I required and then create my Data Table.
Cheers.
So I have an sql database where i get values from via a json API.
I have som problem with deserializing the DateTime variables timeFrom and timeTo.
Right now all the timeFrom and all the timeTo gets tha value of:
{1/1/0001 12:00:00 AM}
Witch is not the correct value...
This is a sample of one booking of a room from the json api:
{
"id": "c49af34d-5479-4304-8acc-30f22a7cd1ef",
"code": 6679,
"timeFrom": "2018-06-13T16:00:00",
"timeTo": "2018-06-13T16:45:00",
"note": null,
"createdDate": "2018-02-13T10:04:14.8",
"room": {
"name": "Rum 1",
"id": "c49af34d-5479-4304-8acc-30f22a7cd1ef",
"seats": 10,
"availableFrom": null,
"availableTo": null,
"roomAttributes": [
{
"id": 1,
"name": "Tv",
"icon": 62060
},
{
"id": 2,
"name": "Wifi",
"icon": 61931
}
]
}
}
And this is how I deserialize the json:
string booking = "https://api.booknings.com/api/company/c49af34d-5479-4304-8acc-30f22a7cd1ef/room/{room.id}/booking";
HttpClient BookingClient = new HttpClient();
string BookingResponse = await BookingClient.GetStringAsync(booking);
var BookingData = JsonConvert.DeserializeObject<List<Bookings>>(response);
foreach (var books in BookingData)
{
string note = books.note;
DateTime TimeFrom = books.timeFrom;
DateTime TimeTo = books.timeTo;
Class2 BookRoom = books.room;
string BookId = books.id;
int code = books.code;
}
This is the class where I have all the properties of the booking:
public class Bookings
{
public string id { get; set; }
public int code { get; set; }
public DateTime timeFrom { get; set; }
public DateTime timeTo { get; set; }
public string note { get; set; }
public DateTime createdDate { get; set; }
public Class2 room { get; set; }
}
So my question is if there is someone who knows what i am doing wrong...
Thanks in avance!
You can use Newtonsoft.Json
var files = JObject.Parse(YourJsonhere);
var recList = files.SelectTokens("$..timeTo").ToList();
string value = recList[0].ToString();
Okay first of all, the answer is probably very simple... But after 45 minutes of trying and googling I just can't figure it out!
So I have some problems getting this Json to parse correctly. I created the classes with http://json2csharp.com/ only it doesn't tell me the code to parse it.
My current classes:
public class Representations
{
public string thumb { get; set; }
public string large { get; set; }
public string full { get; set; }
}
public class Search
{
public string id { get; set; }
public string file_name { get; set; }
public Representations representations { get; set; }
}
public class SearchQuery
{
public List<Search> search { get; set; }
public int total { get; set; }
}
JSON:
{
"search": [
{
"id": "0300",
"file_name": "0300.JPG",
"representations": {
"thumb": "thumb.jpg",
"large": "large.jpg",
"full": "0300.jpg"
},
},
{
"id": "0000",
"file_name": "0000.JPG",
"representations": {
"thumb": "thumb.jpg",
"large": "large.jpg",
"full": "0000.jpg"
},
},
{
"id": "0d00",
"file_name": "0d00.JPG",
"representations": {
"thumb": "thumb.jpg",
"large": "large.jpg",
"full": "0d00.jpg"
},
}
],
"total": 3
}
and code:
searchresults = JsonConvert.DeserializeObject<List<SearchQuery>>(JSONCode);
You should deserialize to a SearchQuery, not List<SearchQuery>:
SearchQuery result = JsonConvert.DeserializeObject<SearchQuery>(JSONCode);
and then use the search property to access the list of search results:
List<Search> searchResults = result.search;