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.
Related
Hi I having following JSON but while Using Deserialize method getting NULL in nested Member here is the sample JSON and corresponding Class object:
{
"status": "success",
"Info": [
{
"Name": "1099589",
"version": "Current Version",
"MoreDetails": [
{
"Name": "1099589",
"state": "IN"
},
{
"Name": "1099768",
"state": "OUT"
}
]
},
{
"Name": "1099768",
"version": "2019"
}
],
"errorCode": "",
"message": ""
}
Class :
public class MoreDetail
{
public string Name { get; set; }
public string state { get; set; }
}
public class Info
{
public string Name { get; set; }
public string version { get; set; }
public IList<MoreDetail> MoreDetails { get; set; }
}
public class Example
{
public string status { get; set; }
public IList<Info> Info { get; set; }
public string errorCode { get; set; }
public string message { get; set; }
}
While I am using
JavaScriptSerializer js = new JavaScriptSerializer();
Example ex = new OfferingPayload();
ex = js.Deserialize<Example> (jsonstring);
I am able to see Example object having Info data as list but MoreDetails member of Info Class is coming NULL.
Can someone suggest what I am missing here ?
Thats because your second "Info" object doesnt have "MoreDetails" property.
{
"Name": "1099768",
"version": "2019"
}
To make it works you can add an empty "MoreDetails" property to your json.
{
"Name": "1099768",
"version": "2019",
"MoreDetails": []
}
Or you can configure your serializer to handle this property as optional. Then it will works fine even if it missing in your json.
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
ok so im not entirely sure how to explain this but ill give it my best shot. i have deserialisation from json working on singular objects, but when i get a list of the objects in json form, it doesnt work, and there are a few extra details outside of the singular objects when in a list of the objects.
the line of code im pretty sure is the problem is
var model = JsonConvert.DeserializeObject<DeserializedObjects.BlockList>(JObject.Parse(json).ToString());
but i cannot figure out how to solve it.
anyway.
this is where the multiple data objects in json from come from:
public static async Task<DeserializedObjects.BlockList> GetUpToTenBlocks(int height)
{
var JData = (dynamic)new JObject();
JData.height = height;
String uri = String.Concat(partialApi, "/local/chain/blocks-after");
var response = await client.PostAsync(uri, new StringContent(JData.ToString(), Encoding.UTF8, "application/json"));
var content = response.Content;
{
var json = await content.ReadAsStringAsync();
var model = JsonConvert.DeserializeObject<DeserializedObjects.BlockList>(JObject.Parse(json).ToString());
Console.WriteLine(model.AtIndex[1].difficulty);
return model;
}
}
which is deserialized to:
public class PrevBlockHash
{
public string data { get; set; }
}
public class Block
{
public int timeStamp { get; set; }
public string signature { get; set; }
public PrevBlockHash prevBlockHash { get; set; }
public int type { get; set; }
public List<object> transactions { get; set; }
public int version { get; set; }
public string signer { get; set; }
public long height { get; set; }
}
public class Datum
{
public object difficulty { get; set; }
public List<object> txes { get; set; }
public Block block { get; set; }
public string hash { get; set; }
}
public class BlockList
{
public List<Datum> AtIndex { get; set; }
}
and this is the json payload:
{
"data": [
{
"difficulty": 11763927507942,
"txes": [],
"block": {
"timeStamp": 167479,
"signature": "bb062d9b5f132b39b9e56de2413bf04928af009587446621da7afd351d
15a2ce7b5504450acf41bc3b19ab71e9bf34722005239d93f05a2318130f85118df40c",
"prevBlockHash": {
"data": "d4875ad2fc74dacfa89a13f24159d14555d3766f4fe2d708a7596f84eba88
31b"
},
"type": 1,
"transactions": [],
"version": 1744830465,
"signer": "00a30788dc1f042da959309639a884d8f6a87086cda10300d2a7c3a0e0891
a4d",
"height": 1001
},
"hash": "f70898011d7343a0823de9c9cf263de29ddf2c16bb78cea626b9af90ea7ec260"
},
{
"difficulty": 11625594628802,
"txes": [],
"block": {
"timeStamp": 167561,
"signature": "116dedf43dd06b9ca634db0e20e06cc93337cdba155bced4d843ece4cc
9a57487d58e9a34d8a0e19bf71d3b7facb15179a87767f0063ebbce7c940cd545d5f01",
"prevBlockHash": {
"data": "f70898011d7343a0823de9c9cf263de29ddf2c16bb78cea626b9af90ea7ec
260"
},
"type": 1,
"transactions": [],
"version": 1744830465,
"signer": "6ecd181da287c9ccb0075336de36427f25cbc216dc6b1f0e87e35e41a39f6
3fe",
"height": 1002
},
"hash": "77b5644c35e0d0d51f8bb967d0d92e0ddb03c4ede6632cb3b7651b7394617562"
},
{
"difficulty": 11538802895169,
"txes": [],
"block": {
"timeStamp": 167624,
"signature": "982574132fdc99b6f484acdd3f1cb5229b2bf78ad7b4e9af3d7a1873da
b987401f8bf808ff749aca70c503f490db1411b6cd89dbb0c1daa24fd580f91d3d9601",
"prevBlockHash": {
"data": "77b5644c35e0d0d51f8bb967d0d92e0ddb03c4ede6632cb3b7651b7394617
562"
},
"type": 1,
"transactions": [],
"version": 1744830465,
"signer": "26a3ac4b24647c77dc87780a95e50cb8d7744966e4569e3ac24e52c532c0c
d0d",
"height": 1003
},
"hash": "1a6d52c6317150d1839790da2c1481d714038c869842f769affbec0fdeec9861"
}
]
}
Try this:
var model = JsonConvert.DeserializeObject<DeserializedObjects.BlockList>(json);
Console.WriteLine(model.data[1].difficulty);
along with, also:
public class BlockList
{
public List<Datum> data { get; set; }
}
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;
This is an example of the Json files that I want to work with:
{
"type": "FeatureCollection",
"totalFeatures": 213,
"features": [
{
"type": "Feature",
"id": "world_contries.1",
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[
[
[
65.53080749511719,
37.248600006103516
],
[
65.6272964477539,
37.33319854736328
]
]
]
]
},
"geometry_name": "geom",
"properties": {
"name": "Afghanistan",
"iso_3_code": "AFG",
"iso_2_code": "AF",
"area": 65209,
"name_1": "Afghanistan",
"gmi_cntry": "AFG",
"region": "Asia",
"pop2005": 25067407,
"name_12": "Afghanistan"
}
},
{
"type": "Feature",
"id": "world_contries.2",
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[
[
[
19.282489776611328,
42.18553924560547
],
[
19.397319793701172,
42.31707000732422
]
]
]
]
},
"geometry_name": "geom",
"properties": {
"name": "Albania",
"iso_3_code": "ALB",
"iso_2_code": "AL",
"area": 2740,
"name_1": "Albania",
"gmi_cntry": "ALB",
"region": "Europe",
"pop2005": 3153731,
"name_12": "Albania"
}
},
]
}
In this type of files I want to have the geometry type and coordinates of all features.
I'm currently using this method to access the file:
public static List<string> getCoords(string path)
{
//List<string> layers = new List<string>();
string url = path;
WebRequest request = WebRequest.Create(url);
request.ContentType = "application/json";
request.Method = "GET";
try
{
WebResponse response = request.GetResponse();
StreamReader responseStream = new StreamReader(response.GetResponseStream());
string responseText = responseStream.ReadToEnd();
JObject o = JObject.Parse(responseText);
dynamic array = JsonConvert.DeserializeObject(responseText);
string type = array["features"].Children()["geometry"]["type"];
response.Close();
}
catch (WebException)
{
;
}
return null;
}
But it's not working. For instance:
array["features"].Children()["geometry"]["type"]
This is an Newtonsoft.JSon.Linq.JEnumerable
When I'm debugging in my Visual Studio, in the results view I can read "MultiPolygon", but I do I extract the value?
I used json2csharp (http://json2csharp.com) to generate some C# classes that match the JSON you provided..
public class Geometry
{
public string type { get; set; }
public List<List<List<List<double>>>> coordinates { get; set; }
}
public class Properties
{
public string name { get; set; }
public string iso_3_code { get; set; }
public string iso_2_code { get; set; }
public int area { get; set; }
public string name_1 { get; set; }
public string gmi_cntry { get; set; }
public string region { get; set; }
public int pop2005 { get; set; }
public string name_12 { get; set; }
}
public class Feature
{
public string type { get; set; }
public string id { get; set; }
public Geometry geometry { get; set; }
public string geometry_name { get; set; }
public Properties properties { get; set; }
}
public class RootObject
{
public string type { get; set; }
public int totalFeatures { get; set; }
public List<Feature> features { get; set; }
}
You could then modify your code so that it deserializes to the RootObject and it will be alot easier to work with instead of dynamic types...
var myObject = JsonConvert.DeserializeObject<RootObject>(responseText);
Then you could access it like this...
foreach (var feature in myObject.features)
{
var geometryType = feature.geometry.type;
....
}
You can simply loop through the JEnumerable to extract each geometry type :
.....
dynamic array = JsonConvert.DeserializeObject(json);
var types = array["features"].Children()["geometry"]["type"];
foreach (string type in types)
{
Console.WriteLine(type);
}