C# class that would represent JSON data - c#

what would the C# class definition look like to represent this JSON data?
{
"accountId": "101",
"website": "www.example.com",
"alternateWebsites": [
{
"website": "site2.example.com"
}
],
"email": "contact#mysite.com",
"alternateEmails": [
{
"email": "sales#example.com"
}
],
"address": {
"street": "234 Main Street",
"city": "San Diego",
"postalCode": "92101",
"state": "CA"
},
"rankingKeywords":
[{
"keyword": "Coffee",
"localArea": "Sacramento, CA"
}]
}

You can use a site like this http://jsonutils.com/
where you paste in your json and it constructs your classes for you. The result of your JSON produced...
public class AlternateWebsite
{
public string website { get; set; }
}
public class AlternateEmail
{
public string email { get; set; }
}
public class Address
{
public string street { get; set; }
public string city { get; set; }
public string postalCode { get; set; }
public string state { get; set; }
}
public class RankingKeyword
{
public string keyword { get; set; }
public string localArea { get; set; }
}
public class Root
{
public string accountId { get; set; }
public string website { get; set; }
public IList<AlternateWebsite> alternateWebsites { get; set; }
public string email { get; set; }
public IList<AlternateEmail> alternateEmails { get; set; }
public Address address { get; set; }
public IList<RankingKeyword> rankingKeywords { get; set; }
}

You could convert this with a service like http://json2csharp.com/. Enter the JSON and it will spit out C# model classes. Then, add them either as a class, or using Entity Framework (depending on your objective) into your project.
C# version:
public class AlternateWebsite
{
public string website { get; set; }
}
public class AlternateEmail
{
public string email { get; set; }
}
public class Address
{
public string street { get; set; }
public string city { get; set; }
public string postalCode { get; set; }
public string state { get; set; }
}
public class RankingKeyword
{
public string keyword { get; set; }
public string localArea { get; set; }
}
public class RootObject
{
public string accountId { get; set; }
public string website { get; set; }
public List<AlternateWebsite> alternateWebsites { get; set; }
public string email { get; set; }
public List<AlternateEmail> alternateEmails { get; set; }
public Address address { get; set; }
public List<RankingKeyword> rankingKeywords { get; set; }
}

Related

Net Core - AutoMapper an entity with his parent

I've tried to automap an entity with his parent but it's not working as I expected.
I have a company which can have some categories.
When I tried to get my category and his company inside, I have some fields I don't want to get (for example the siret, the connections or the passwords fields).
This is the result :
{
"id": 2,
"name": "Toot3",
"products": [],
"company": {
"id": 1,
"siret": "10000000000000",
"name": "Tootland",
"postal": 33000,
"city": "Bordeaux",
"country": "France",
"address": null,
"mail": "xxx",
"status": "waiting",
"created": "2020-07-08T18:51:52.051339",
"lastConnection": "2020-07-13T20:41:05.1292985",
"passwordHash": "xxx",
"passwordSalt": "xxx",
"categs": []
},
"companyId": 1
}
My request to get all the categories and his parent :
public async Task<IEnumerable<Categ>> GetAllWithProducts()
{
return await _context.Categ
.Include(cm => cm.Products)
.Include(cm => cm.Company)
.ToListAsync();
}
This is my company class :
public class Company
{
public const string STATUS_WAITING = "waiting";
public const string STATUS_VALIDATED = "validated";
public const string STATUS_REJECTED = "rejected";
public int Id { get; set; }
public string Siret { get; set; }
public string Name { get; set; }
public int Postal { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string Address { get; set; }
public string Mail { get; set; }
public string Status { get; set; }
public DateTime Created { get; set; }
public DateTime LastConnection { get; set; }
public byte[] PasswordHash { get; set; }
public byte[] PasswordSalt { get; set; }
public ICollection<Categ> Categs { get; set; }
}
Then my categ class :
public class CategMagazine
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Product> Products { get; set; }
public Company Company { get; set; }
public int CompanyId { get; set; }
}
An extract of my AutoMapperProfiles class :
CreateMap<Company, CompanyForListDto>();
CreateMap<Categ, CategForListDto>()
.ForMember(dest => dest.Company,
opt => opt.MapFrom(src => src.Company));
The CompanyForListDto
public class CompanyForListDto
{
public string Name { get; set; }
public int Postal { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string Address { get; set; }
}
The CategForListDto
public class CategForListDto
{
public int Id { get; set; }
public string Name { get; set; }
public CompanyForListDto Company { get; set; }
}
Thanks you in advance for your help.
Best regards.
(PS : Sorry for my bad english)

Deserialize JSON to List

I have this Json:
{
"trades": [
{
"id": "4004",
"instrument": "EUR_USD",
"price": "1.08938",
"openTime": "2020-02-26T12:15:32.309973340Z",
"initialUnits": "1",
"initialMarginRequired": "0.0363",
"state": "OPEN",
"currentUnits": "1",
"realizedPL": "0.0000",
"financing": "0.0000",
"dividendAdjustment": "0.0000",
"unrealizedPL": "-0.0026",
"marginUsed": "0.0362",
"takeProfitOrder": {
"id": "4005",
"createTime": "2020-02-26T12:15:32.309973340Z",
"type": "TAKE_PROFIT",
"tradeID": "4004",
"price": "1.09099",
"timeInForce": "GTC",
"triggerCondition": "DEFAULT",
"state": "PENDING"
}
}
],
"lastTransactionID": "4010"
}
And Classes:
public class TakeProfitOrder
{
public string id { get; set; }
public string createTime { get; set; }
public string type { get; set; }
public string tradeID { get; set; }
public string price { get; set; }
public string timeInForce { get; set; }
public string triggerCondition { get; set; }
public string state { get; set; }
}
public class Trade
{
public string id { get; set; }
public string instrument { get; set; }
public string price { get; set; }
public string openTime { get; set; }
public string initialUnits { get; set; }
public string initialMarginRequired { get; set; }
public string state { get; set; }
public string currentUnits { get; set; }
public string realizedPL { get; set; }
public string financing { get; set; }
public string dividendAdjustment { get; set; }
public string unrealizedPL { get; set; }
public string marginUsed { get; set; }
public TakeProfitOrder takeProfitOrder { get; set; }
}
public class RootObject
{
public List<Trade> trades { get; set; }
public string lastTransactionID { get; set; }
}
I deserialize with :
var result = JsonConvert.DeserializeObject<RootObject>(Json);
var price = result.trades.Select(p => p.price).ToList();
price.ForEach(Console.WriteLine);
It works. I can access "price" in "trades", but I do not know how to access the "price" in "takeProfitOrder". I need the value of "price" from "takeProfitOrder" in to a list. I am sure it is something very simple but I cannot figure out how to do it, even after looking at some similar examples.
Can somebody please help me?
It's simple
result.trades.Select(p => p.takeProfitOrder.price)
You should understand better from this example
foreach (Trade trade in result.trades)
{
TakeProfitOrder takeProfitOrder = trade.takeProfitOrder;
Console.WriteLine(takeProfitOrder.price);
}

How to Deserialize deeply nested json array in asp.net C#

JSon String is given below:
{
"properties": {
"jci": [
{
"firstName": "Henk",
"lastName": "de Vries",
"Photo": "http://s3.amazonaws.com/mendeley-photos/6a/bd/6abdab776feb7a1fd4e5b4979ea9c5bfc754fd29.png",
"Title": "Dr.",
"Position": "Head of research group",
"Institution": "Vrije Universiteit Amsterdam",
"Fields_of_interest": ["medicine", "computer science"],
"emailAddress": "henk.de.vries#science.com",
"editorship": [
{
"title": "Dr.",
"editorial_role": "Editor in chief",
"date_start": 1460116283,
"date_end": 1460116283,
"publisher": {
"name": "Elsevier",
"role": "Project manager",
"emailAddress": "journal#elsevier.com"
}
}
]
}
],
"sid": [
{
"firstName": "Henk",
"lastName": "de Vries",
"Title": "Dr.",
"primary organisation": "Vrije Universiteit Amsterdam",
"emailAddress": "henk.de.vries#science.com",
"editorship": [
{
"title": "Dr.",
"editorial_role": "Editor in chief",
"publication_year": 2012
}
]
}
]
}
}
I have written code to deserialization
JavaScriptSerializer ser = new JavaScriptSerializer();
JsonTest foo = new JsonTest();
foo = (JsonTest)ser.Deserialize<JsonTest>(JSONString);
public class JsonTest
{
public properties properties { get; set; }
}
public class properties
{
public List<jci> jci { get; set; }
public List<sid>sid { get; set; }
}
public class jci
{
public string firstName { get; set; }
public string lastName { get; set; }
public string Photo { get; set; }
public string Position { get; set; }
public string Institution { get; set; }
public string emailAddress { get; set; }
public string Title { get; set; }
public List<string> Fields_of_interest { get; set; }
public List<editorship> editorship { get; set; }
}
public class editorship
{
public string title { get; set; }
public string editorial_role { get; set; }
public string date_start { get; set; }
public string date_end { get; set; }
public Dictionary<string, string> publisher { get; set; }
}
in this code there are 2 arrays of object called "editorship".. I have created "editorship" class for "jci".. how to access the values of editorship array of sid...?
Using json2csharp i generated these classes based on your JSON
public class Publisher
{
public string name { get; set; }
public string role { get; set; }
public string emailAddress { get; set; }
}
public class Editorship
{
public string title { get; set; }
public string editorial_role { get; set; }
public int date_start { get; set; }
public int date_end { get; set; }
public Publisher publisher { get; set; }
}
public class Jci
{
public string firstName { get; set; }
public string lastName { get; set; }
public string Photo { get; set; }
public string Title { get; set; }
public string Position { get; set; }
public string Institution { get; set; }
public List<string> Fields_of_interest { get; set; }
public string emailAddress { get; set; }
public List<Editorship> editorship { get; set; }
}
public class Editorship2
{
public string title { get; set; }
public string editorial_role { get; set; }
public int publication_year { get; set; }
}
public class Sid
{
public string firstName { get; set; }
public string lastName { get; set; }
public string Title { get; set; }
public string primary_organisation { get; set; }
public string emailAddress { get; set; }
public List<Editorship2> editorship { get; set; }
}
public class Properties
{
public List<Jci> jci { get; set; }
public List<Sid> sid { get; set; }
}
public class RootObject
{
public Properties properties { get; set; }
}
You can then access your editorial values like this:
JavaScriptSerializer serializer = new JavaScriptSerializer();
var collection = serializer.Deserialize<RootObject>(jsonString);
foreach (var j in collection.properties.sid)
{
Console.Write(j.editorship);
}
On a side note, you should consider using names that are more readable then jci and sid

Issues with deserializing Json in C#

I have some json like this:
{
"status": "OK",
"result": {
"#type": "address_result__201301",
"barcode": "1301013030001010212212333002003031013",
"bsp": "044",
"dpid": "99033785",
"postcode": "4895",
"state": "QLD",
"suburb": "COOKTOWN",
"city": null,
"country": "AUSTRALIA"
},
"search_date": "03-12-2014 15:31:03",
"search_parameters": {},
"time_taken": 636,
"transaction_id": "f8df8791-531e-4043-9093-9f35881f6bb9",
"root_transaction_id": "a1fa1426-b973-46ec-b61b-0fe5518033de"
}
Then I created some classes:
public class Address
{
public string status { get; set; }
public Result results { get; set; }
public string search_date { get; set; }
public SearchParameters search_parameters { get; set; }
public int time_taken { get; set; }
public string transaction_id { get; set; }
public string root_transaction_id { get; set; }
}
public class Result
{
public string #type { get; set; }
public string barcode { get; set; }
public string bsp { get; set; }
public string dpid { get; set; }
public string postcode { get; set; }
public string state { get; set; }
public string suburb { get; set; }
public string city { get; set; }
public string country { get; set; }
}
public class SearchParameters
{
}
Finally, I use these code to get Json data:
string result = "Above json";
JavaScriptSerializer json = new JavaScriptSerializer();
Address add = json.Deserialize<Address>(result);
I see that, add.status, add.search_date... etc have values, but add.results is null.
What is wrong with my code?
I think the issue is using #type as illegal identifier. Try using [DataMember(Name = "#type")] before public string #type { get; set; }. Add a [DataContract] before public class Address.
Hence, your final code will be,
[DataContract]
public class Result
{
[DataMember(Name = "#type")]
public string #type { get; set; }
public string barcode { get; set; }
public string bsp { get; set; }
public string dpid { get; set; }
public string postcode { get; set; }
public string state { get; set; }
public string suburb { get; set; }
public string city { get; set; }
public string country { get; set; }
}

Deserialize json to c#

How should my C# sharp object look like, I would like to deserialize the following JSON string to a C# object.
{
"PersonId": "XXXXXXXXXXXXXX",
"Name": "XXXXXXXX",
"HobbiesCollection":
{"Hobby":
[
{
"type": "RUNNING",
"id": 44,
"description": "sprinting and sprinting?"
},
{
"type": "RUNNING",
"id": 45,
"description": "jogging and jogging"
}
]
}
}
Here is what is generated in VS2013
public class Rootobject
{
public string PersonId { get; set; }
public string Name { get; set; }
public Hobbiescollection HobbiesCollection { get; set; }
}
public class Hobbiescollection
{
public Hobby[] Hobby { get; set; }
}
public class Hobby
{
public string type { get; set; }
public int id { get; set; }
public string description { get; set; }
}
You can use VS2012/2013 feature Edit/Paste Special/Paste JSON As Classes to simplify this process.
There is a online tool you can make C# class from your String
JSON to Csharp
public class Hobby
{
public string type { get; set; }
public int id { get; set; }
public string description { get; set; }
}
public class HobbiesCollection
{
public List<Hobby> Hobby { get; set; }
}
public class RootObject
{
public string PersonId { get; set; }
public string Name { get; set; }
public HobbiesCollection HobbiesCollection { get; set; }
}

Categories