C# how should I create this complex Model - c#

I will create a C# Model, but I am not sure, what is the best way to do it. Maybe you can help me.
It is about a query of customer data.
Graphically it looks like this. Our customer can design the request very individually. He can link all fields that exist with one another
And the json object to my controller is like this.
{
"predicates":[
{
"type":"role",
"attribute":"role",
"comparison":"eq",
"value":"user_role"
},
{
"type":"and",
"predicates":[
{
"type":"or",
"predicates":[
{
"type":"boolean",
"attribute":"custom_data.has_paid",
"comparison":"unknown",
"value":null
},
{
"type":"boolean",
"attribute":"custom_data.has_paid",
"comparison":"false",
"value":null
}
]
},
{
"type":"string",
"attribute":"custom_data.plan_aktiv",
"comparison":"eq",
"value":"freeMember"
},
{
"type":"date",
"attribute":"custom_data.ipnFree_ends",
"comparison":"gt",
"value":"30"
},
{
"type":"integer",
"attribute":"session_count",
"comparison":"gt",
"value":"15"
}
]
}
],
"segment_id":"61697d1fc753cca611bf7034",
"page":1,
"per_page":25,
"sort_by":"remote_created_at",
"sort_direction":"desc"
}
My idea of the model is following
public class Predicate
{
public string type { get; set; }
public string attribute { get; set; }
public string comparison { get; set; }
public string value { get; set; }
public List<Predicate> predicates { get; set; }
}
public class Root
{
public List<Predicate> predicates { get; set; }
public string segment_id { get; set; }
public int page { get; set; }
public int per_page { get; set; }
public string sort_by { get; set; }
public string sort_direction { get; set; }
}
But I am not sure, if its the best model for all querys. What do you mean? Thanks for your help
Do you need more information about that case?

Related

How to bind this json and read specific key value

I have below json which I would like to read it in a list. below are the classes and model defined and the code by which I am trying to read. I am getting null value on binding. I am not sure how should i achieve this. So for example if I have multiple rules, I would like to read each one based on the condition passed. Please see my last sample code for better understanding.
Sample Json:
{"TableStorageRule": { "Rules": [ {
"Name": "filterRule1",
"DataFilter":
{
"DataSetType": "Settings1"
},
"TableSettings":
{
"AzureTable": {
"Account": "account1",
"Table": "table1",
"Key": "key1"
},
"SchemaBaseUri": "https://test.web.core.windows.net/"
}
},
{
"Name": "filterRule2",
"DataFilter":
{
"DataSetType": "Settings2"
},
"TableSettings":
{
"AzureTable": {
"Account": "account2",
"Table": "table2",
"Key": "key2"
},
"SchemaBaseUri": "https://test2.web.core.windows.net/"
}
}
] }}
Model and Code:
public class TableStoreSettings
{
public class AzureTableSettings
{
public string Account { get; set; }
public string Key { get; set; }
public string Table { get; set; }
}
public AzureTableSettings AzureTable { get; set; }
public Uri SchemaBaseUri { get; set; }
}
public class TableStorageRule
{
public string Name { get; set; }
public TwisterDataFilter DataFilter { get; set; }
public TableStoreSettings TableSettings { get; set; }
}
public class TableStorageConfiguration
{
public IEnumerable<TableStorageRule> Rules { get; set; } = new List<TableStorageRule>();
}
code by which I am trying to read:
var builder = new ConfigurationBuilder()
.SetBasePath(Path.Combine(Root))
.AddJsonFile("appsettings.json", optional: false);
var config = builder.Build();
var tableStorageOutput = new TableStorageRule();
config.GetSection("TableStorageRule").Bind(tableStorageOutput);
var nameOfFilter = tableStorageOutput.Name;
if (tableStorageOutput.Name == "filterRule1")
{
var accountname = tableStorageOutput.TableSettings.AzureTable.Account;
}
on above I only get first filtername1 , i dont get other filternames and so on...though on GetSection() i see all the values in quick watch.
this is correct models from your JSON file :
public class DataFilter {
public string DataSetType { get; set; }
}
public class AzureTable {
public string Account { get; set; }
public string Table { get; set; }
public string Key { get; set; }
}
public class TableSettings {
public AzureTable AzureTable { get; set; }
public string SchemaBaseUri { get; set; }
}
public class Rule {
public string Name { get; set; }
public DataFilter DataFilter { get; set; }
public TableSettings TableSettings { get; set; }
}
public class TableStorageRule {
public List<Rule> Rules { get; set; }
}
public class Root {
public TableStorageRule TableStorageRule { get; set; }
}
for test you can read your JSON file and get values (maybe change models solve your problem in your code):
string json = File.ReadAllText(jsonFilePath);
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(json);

Invalid type when generate the json?

I've this json:
{
"page": "36",
"bookmaker_urls": {
"13": [{
"link": "http://www.bet365.com/home/?affiliate=365_179024",
"name": "Bet 365"
}]
},
"block_service_id": "competition_summary_block_competitionmatchessummary",
"round_id": "36003",
"outgroup": "",
"view": "1",
"competition_id": "13"
}
I've inserted this on this tool: http://json2csharp.com/
this will return:
public class __invalid_type__13
{
public string link { get; set; }
public string name { get; set; }
}
public class BookmakerUrls
{
public List<__invalid_type__13> __invalid_name__13 { get; set; }
}
public class RootObject
{
public int page { get; set; }
public BookmakerUrls bookmaker_urls { get; set; }
public string block_service_id { get; set; }
public int round_id { get; set; }
public bool outgroup { get; set; }
public int view { get; set; }
public int competition_id { get; set; }
}
why there is an invalid type?
13 is not a valid property name in .NET, and the tool you're using seems to try to map each JSON property to .NET Class property.
What you probably want is bookmaker_urls to be a dictionary:
public class BookmakerUrl
{
public string link { get; set; }
public string name { get; set; }
}
public class RootObject
{
public int page { get; set; }
public Dictionary<string, List<BookmakerUrl>> bookmaker_urls { get; set; }
public string block_service_id { get; set; }
public int round_id { get; set; }
public bool outgroup { get; set; }
public int view { get; set; }
public int competition_id { get; set; }
}
The generator generates the name of properties and types from the name of properties in the Json.
There is a property "13" in the Json. A name starting with a digit would not be a valid name in c#.
So, the generator just adds the prefix "invalid_name" or "invalid_type" to the generated names. This does not mean that there was any problem or that you cannot use the generated code.

Serializing Json to c# Class throwing error

I have a JSON returning from web like this
{
"data": {
"normal_customer": {
"0": {
"id": 1,
"name": "ALPHY"
}
},
"1": {
"id": 2,
"name": "STEVEN"
}
},
"luxury_customer": {
"3": {
"id": 8,
"name": "DEV"
}
}
}
}
I have created c# classes
public class StandardCustomers
{
public List<CustomersDetails> Customers_Details { get; set; }
}
public class CustomersDetails
{
[JsonProperty("id")]
public int id { get; set; }
[JsonProperty("name")]
public string name { get; set; }
public class LuxuryCustomers
{
public List<CustomersDetails> Customers_Details { get; set; }
}
public class Data
{
public StandardCustomers standard_Customers { get; set; }
public LuxuryCustomers luxury_Customers { get; set; }
}
public class RootObject
{
public Data data { get; set; }
}
}
When I use deserialize the response from the website using below c# code
var result1 = JsonConvert.DeserializeObject<Data>(response);
but result1.luxury_customers contains customerdetails which is null.
As suggested by #hellostone, I have modified to rootdata, then also
result1.luxury_customers contains customerdetails is null.
Any idea how to deserialize to c# class
When we pasted Json to visual studio, it generated classes as below
public class Rootobject
{
public Data data { get; set; }
}
public class Data
{
public Standard_Customers standard_Customers { get; set; }
public Luxury_Customers luxury_Customers { get; set; }
}
public class Standard_Customers
{
public _0 _0 { get; set; }
public _1 _1 { get; set; }
public _2 _2 { get; set; }
public _4 _4 { get; set; }
public _5 _5 { get; set; }
}
public class _0
{
public int id { get; set; }
public string name { get; set; }
}
individual classes are generated in standard customers , can we use list for this
I guess the problem is that index in luxury_customers starting not from zero. Try to use Dictionary<string,CustomersDetails> in LuxuryCustomers instead List<CustomersDetails>.
I've managed to deserialize Json with this classes:
public class CustomersDetails
{
[JsonProperty("id")]
public int id { get; set; }
[JsonProperty("name")]
public string name { get; set; }
}
public class Data
{
public Dictionary<string, CustomersDetails> normal_customer { get; set; }
public Dictionary<string,CustomersDetails> luxury_customer { get; set; }
}
public class RootObject
{
public Data data { get; set; }
}
Deserialization code:
var result = JsonConvert.DeserializeObject<RootObject>(text);
P.S. I've remove one closing bracket after "ALPHY" element, to make Json valid, I hope it was typo and you're getting valid Json.
Your json string doesn't match with your defined classes. Your Json string should look like this if you want to preserve your class structure:
{
"data":{
"standard_Customers":{
"Customers_Details":[
{
"id":1,
"name":"ALPHY"
},
{
"id":2,
"name":"STEVEN"
}
]
},
"luxury_Customers":{
"Customers_Details":[
{
"id":8,
"name":"DEV"
}
]
}
}
}
Pay attention to the square brackets at the "Customers_Details" attribute.
Then the:
var result1 = JsonConvert.DeserializeObject<RootObject>(response);
call, will give you the right object back and it shouldn't be null, when using your class structure:
public class StandardCustomers
{
public List<CustomersDetails> Customers_Details { get; set; }
}
public class CustomersDetails
{
[JsonProperty("id")]
public int id { get; set; }
[JsonProperty("name")]
public string name { get; set; }
}
public class LuxuryCustomers
{
public List<CustomersDetails> Customers_Details { get; set; }
}
public class Data
{
public StandardCustomers standard_Customers { get; set; }
public LuxuryCustomers luxury_Customers { get; set; }
}
public class RootObject
{
public Data data { get; set; }
}

processing api output in vb.net or c#

After making an api call, the example below shows what a typical response would be.
{
"code":"success",
"message":"Data retrieved for email",
"data":{
"attributes":{
"EMAIL":"example#example.net",
"NAME" : "Name",
"SURNAME" : "surname"
},
"blacklisted":1,
"email":"example#example.net",
"entered":"2014-01-15",
"listid":[8],
"message_sent":[{
"camp_id" : 2,
"event_time" : "2013-12-18"
},
{ "camp_id" : 8,
"event_time" : "2014-01-03"
},
{ "camp_id" : 11,
"event_time" : "2014-01-07"
}],
"hard_bounces":[{
"camp_id" : 11,
"event_time" : "2014-01-07"
}],
"soft_bounces":[],
"spam":[{
"camp_id" : 2,
"event_time" : "2014-01-09"
}],
"unsubscription":{
"user_unsubscribe":[
{
"event_time":"2014-02-06",
"camp_id":2,
"ip":"1.2.3.4"
},
{
"event_time":"2014-03-06",
"camp_id":8,
"ip":"1.2.3.4"
}
],
"admin_unsubscribe":[
{
"event_time":"2014-04-06",
"ip":"5.6.7.8"
},
{
"event_time":"2014-04-16",
"ip":"5.6.7.8"
}
]
},
"opened":[{
"camp_id" : 8,
"event_time" : "2014-01-03",
"ip" : "1.2.3.4"
}],
"clicks":[],
"transactional_attributes":[
{
"ORDER_DATE":"2015-07-01",
"ORDER_PRICE":100000,
"ORDER_ID":"1"
},
{
"ORDER_DATE":"2015-07-05",
"ORDER_PRICE":500000,
"ORDER_ID":"2"
}
],
"blacklisted_sms":1
}
}
What I need to do is to be able to read / find and attribute name and its corresponding value. I also need to know the value of blacklisted.
I don't know how to interpret the output given to easily find and read attributes and their values and also get the value of blacklisted.
Maybe if I can get it into an array, I can cycle through the array to find the value pair I am looking for? Or maybe I am overthinking it and their is an easier way.
Please note: This example only shows 3 attribute:value pairs. other calls may output more than three attribute:value pairs.
The simplest way is: You are getting the response in the JSON format and you just need it to be seralized with the use of classes and Json.NET
public class Rootobject
{
public string code { get; set; }
public string message { get; set; }
public Data data { get; set; }
}
public class Data
{
public Attributes attributes { get; set; }
public int blacklisted { get; set; }
public string email { get; set; }
public string entered { get; set; }
public int[] listid { get; set; }
public Message_Sent[] message_sent { get; set; }
public Hard_Bounces[] hard_bounces { get; set; }
public object[] soft_bounces { get; set; }
public Spam[] spam { get; set; }
public Unsubscription unsubscription { get; set; }
public Opened[] opened { get; set; }
public object[] clicks { get; set; }
public Transactional_Attributes[] transactional_attributes { get; set; }
public int blacklisted_sms { get; set; }
}
public class Attributes
{
public string EMAIL { get; set; }
public string NAME { get; set; }
public string SURNAME { get; set; }
}
public class Unsubscription
{
public User_Unsubscribe[] user_unsubscribe { get; set; }
public Admin_Unsubscribe[] admin_unsubscribe { get; set; }
}
public class User_Unsubscribe
{
public string event_time { get; set; }
public int camp_id { get; set; }
public string ip { get; set; }
}
public class Admin_Unsubscribe
{
public string event_time { get; set; }
public string ip { get; set; }
}
public class Message_Sent
{
public int camp_id { get; set; }
public string event_time { get; set; }
}
public class Hard_Bounces
{
public int camp_id { get; set; }
public string event_time { get; set; }
}
public class Spam
{
public int camp_id { get; set; }
public string event_time { get; set; }
}
public class Opened
{
public int camp_id { get; set; }
public string event_time { get; set; }
public string ip { get; set; }
}
public class Transactional_Attributes
{
public string ORDER_DATE { get; set; }
public int ORDER_PRICE { get; set; }
public string ORDER_ID { get; set; }
}
Use Newtonsoft.Json library. One of the most powerful library.Parse your JSON to strongly typed C# object using json2csharp.com then just deserialize the string.
var model= JsonConvert.DeserializeObject<Classname>(result);
You'll need JSON.Net. Pasrse your JSON to strongly typed C# object using json2csharp.com then just deserialize the string using JsonConvert.Deserialize<RootObject>().
One way would be to:
a) Copy your JSON to Clipboard (CTRL+C)
b) On a Visual Studio class, click on EDIT-> Paste Special -> Paste JSON as classes. This will create the classes equivalent of your JSON for you. Your main object would be named as "Rootobject" and you can change this to whatever name you want.
c) Add System.Web.Extensions to your references
d) You can convert your JSON to class like so:
JavaScriptSerializer serializer = new JavaScriptSerializer();
Rootobject rootObject = serializer.Deserialize<Rootobject>(JsonString);
Where JsonString is your API output.

extract data from json in asp.net c#

I'm trying to extract some data from json. I've been looking for a solution either in JSS or Json.net but haven't been able to figure this problem out. this is how my Json looks like:
Note: i Have tested and the mapping and decentralization works! I'm looking for a way to extract specifc data from the json!
Thanks in Advance!
{
"tasks":[
{
"id":"tmp_fk1345624806538",
"name":"Gantt editor ",
"code":"",
"level":0,
"status":"STATUS_ACTIVE",
"start":1346623200000,
"duration":5,
"end":1347055199999,
"startIsMilestone":false,
"endIsMilestone":false,
"assigs":[
{
"resourceId":"tmp_3",
"id":"tmp_1345625008213",
"roleId":"tmp_1",
"effort":7200000
}
],
"depends":"",
"description":"",
"progress":0
},
{
"id":"tmp_fk1345624806539",
"name":"phase 1",
"code":"",
"level":1,
"status":"STATUS_ACTIVE",
"start":1346623200000,
"duration":2,
"end":1346795999999,
"startIsMilestone":false,
"endIsMilestone":false,
"assigs":[
{
"resourceId":"tmp_1",
"id":"tmp_1345624980735",
"roleId":"tmp_1",
"effort":36000000
}
],
"depends":"",
"description":"",
"progress":0
},
{
"id":"tmp_fk1345624789530",
"name":"phase 2",
"code":"",
"level":1,
"status":"STATUS_SUSPENDED",
"start":1346796000000,
"duration":3,
"end":1347055199999,
"startIsMilestone":false,
"endIsMilestone":false,
"assigs":[
{
"resourceId":"tmp_2",
"id":"tmp_1345624993405",
"roleId":"tmp_2",
"effort":36000000
}
],
"depends":"2",
"description":"",
"progress":0
}
],
"resources":[
{
"id":"tmp_1",
"name":"Resource 1"
},
{
"id":"tmp_2",
"name":"Resource 2"
},
{
"id":"tmp_3",
"name":"Resource 3"
}
],"roles":[
{
"id":"tmp_1",
"name":"Project Manager"
},
{
"id":"tmp_2",
"name":"Worker"
}
],
"canWrite":true,
"canWriteOnParent":true,
"selectedRow":0,
"deletedTaskIds":[],
}
i've already mapped as follow
public class Rootobject
{
public Task[] tasks { get; set; }
public Resource[] resources { get; set; }
public Role[] roles { get; set; }
public bool canWrite { get; set; }
public bool canWriteOnParent { get; set; }
public int selectedRow { get; set; }
public object[] deletedTaskIds { get; set; }
}
public class Task
{
public string id { get; set; }
public string name { get; set; }
public string code { get; set; }
public int level { get; set; }
public string status { get; set; }
public long start { get; set; }
public int duration { get; set; }
public long end { get; set; }
public bool startIsMilestone { get; set; }
public bool endIsMilestone { get; set; }
public Assig[] assigs { get; set; }
public string depends { get; set; }
public string description { get; set; }
public int progress { get; set; }
}
public class Assig
{
public string resourceId { get; set; }
public string id { get; set; }
public string roleId { get; set; }
public int effort { get; set; }
}
public class Resource
{
public string id { get; set; }
public string name { get; set; }
}
public class Role
{
public string id { get; set; }
public string name { get; set; }
}
and I need to extract following information from my json.(from specific Task in may json! for example the first one with id : tmp_fk1345624806538 ).
Note: i'm getting my json from a json file as follow:
string startDate; // this is what i need to extract
string endDate; // this is what i need to extract
string Progress; // this is what i need to extract
public void load()
{
GC.GClass l = new GC.GClass();
string jsonString = l.load(); // i get my json from a json file
Rootobject project = JsonConvert.DeserializeObject<Rootobject>(jsonString);
}
You can use LINQ to query the object quickly.
Task task = project.tasks.FirstOrDefault(t=> t.id == "tmp_fk1345624806538");
Test task, and if null then there was not task with matching id. If you are sure that there will be a matching task your can just use .First(), but it will throw an exception if there is no match in the list
You'll need to add a using System.Linq; if you don't have that already.

Categories