How do i create nested json? - json

Help please. I am trying to use Newtonsoft to serialize the following and can't get it to work. The resulting JSON should look like this Extract from Postman. I just cannot figure out how to structure the adding of the data before running the serialization
Anyone able to point me in the right direction?
Required JSON output
{
"Line": [
{
"Id": "1",
"LineNum": 1,
"Description": "Test Sales Description",
"Amount": 100,
"DetailType": "SalesItemLineDetail",
"SalesItemLineDetail": {
"ItemRef": {
"value": "3",
"name": "Test:Test Item"
},
"UnitPrice": 100,
"Qty": 1,
"ItemAccountRef": {
"value": "6",
"name": "Sales"
},
"TaxCodeRef": {
"value": "6"
}
}
},
{
"Amountlin": 0,
"DetailType": "SubTotalLineDetail",
"SubTotalLineDetail": {}
}
],
"TxnTaxDetail": {
"TotalTax": 0,
"TaxLine": [
{
"Amount": 0,
"DetailType": "TaxLineDetail",
"TaxLineDetail": {
"TaxRateRef": {
"value": "7"
},
"PercentBased": true,
"TaxPercent": 20,
"NetAmountTaxable": 0
}
}
]
},
"CustomerRef": {
"value": "2",
"name": "Test Company"
},
"BillAddr": {
"Id": "3",
"Line1": "21 TEST TEST",
"Line2": "TEST",
"City": "TEST",
"Country": "United Kingdom",
"PostalCode": "POSTCODE"
},
"ShipAddr": {
"Id": "3",
"Line1": "21 TEST TEST",
"Line2": "TEST",
"City": "TEST",
"Country": "United Kingdom",
"PostalCode": "POSTCODE"
}
}
I have created the following objects
public class ItemRef
{
public string value { get; set; }
public string name { get; set; }
}
public class ItemAccountRef
{
public string value { get; set; }
public string name { get; set; }
}
public class TaxCodeRef
{
public string value { get; set; }
}
public class SalesItemLineDetail
{
public ItemRef ItemRef { get; set; }
public int UnitPrice { get; set; }
public int Qty { get; set; }
public ItemAccountRef ItemAccountRef { get; set; }
public TaxCodeRef TaxCodeRef { get; set; }
}
public class SubTotalLineDetail
{
}
public class Line
{
public string Id { get; set; }
public int LineNum { get; set; }
public string Description { get; set; }
public int Amount { get; set; }
public string DetailType { get; set; }
public SalesItemLineDetail SalesItemLineDetail { get; set; }
public SubTotalLineDetail SubTotalLineDetail { get; set; }
}
public class TaxRateRef
{
public string value { get; set; }
}
public class TaxLineDetail
{
public TaxRateRef TaxRateRef { get; set; }
public bool PercentBased { get; set; }
public int TaxPercent { get; set; }
public int NetAmountTaxable { get; set; }
}
public class TaxLine
{
public int Amount { get; set; }
public string DetailType { get; set; }
public TaxLineDetail TaxLineDetail { get; set; }
}
public class TxnTaxDetail
{
public int TotalTax { get; set; }
public List<TaxLine> TaxLine { get; set; }
}
public class CustomerRef
{
public string value { get; set; }
public string name { get; set; }
}
public class BillAddr
{
public string Id { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string PostalCode { get; set; }
}
public class ShipAddr
{
public string Id { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string PostalCode { get; set; }
}
public class Root
{
public List<Line> Line { get; set; }
public TxnTaxDetail TxnTaxDetail { get; set; }
public CustomerRef CustomerRef { get; set; }
public BillAddr BillAddr { get; set; }
public ShipAddr ShipAddr { get; set; }
}

You need the set properties of the objects:
ItemRef itemRef = new ItemRef();
itemRef.value = "1";
SalesItemLineDetail salesItemLineDetail = new SalesItemLineDetail();
salesItemLineDetail.ItemRef = itemRef;
Line line = new Line();
line.Id = "1";
line.LineNum = 1;
line.SalesItemLineDetail = salesItemLineDetail;
Root root = new Root();
root.Line = new List<Line>();
root.Line.Add(line);
string body = JsonConvert.SerializeObject(root);

Related

how to return a property based on another property condition using LINQ in .NET Core

{
"value": [{
"odata.type": "SP.User",
"odata.id": "https://www.test.com/_api/Web/GetUserById(37)",
"odata.editLink": "Web/GetUserById(37)",
"Id": 37,
"IsHiddenInUI": false,
"LoginName": "i:0#.w|domain\\jos",
"Title": "Mr joseph",
"PrincipalType": 1,
"Email": "joe#yopmail.com",
"IsEmailAuthenticationGuestUser": false,
"IsShareByEmailGuestUser": false,
"IsSiteAdmin": false,
"UserId": {
"NameId": "s-1-5-21-2613750078-2161710047-3166685486-1473",
"NameIdIssuer": "urn:office:idp:activedirectory"
}
}, {
"odata.type": "SP.User",
"odata.id": "https://www.test.com/_api/Web/GetUserById(90)",
"odata.editLink": "Web/GetUserById(90)",
"Id": 90,
"IsHiddenInUI": false,
"LoginName": "i:0#.w|domain\\pam",
"Title": "anthony",
"PrincipalType": 1,
"Email": "anthony#yopmail.com",
"IsEmailAuthenticationGuestUser": false,
"IsShareByEmailGuestUser": false,
"IsSiteAdmin": false,
"UserId": {
"NameId": "s-1-5-21-2613750078-2161710047-3166685486-1437",
"NameIdIssuer": "urn:office:idp:activedirectory"
}
}
}
after deserializing this JSON I want to get the Title based on the Id so lets say if the Id = 37 I want to return a string that contain Mr joseph. is it possible to do this using LINQ? thank you for your help in advance...
I am desiralizing to this class:
public class UsersInformationValue
{
[JsonProperty("odata.type")]
public string Odata_Type { get; set; }
[JsonProperty("odata.id")]
public string Odata_Id { get; set; }
[JsonProperty("odata.editlink")]
public string Odata_EditLink { get; set; }
public int Id { get; set; }
public bool IsHiddenInUI { get; set; }
public string LoginName { get; set; }
public string Title { get; set; }
public int PrincipalType { get; set; }
public string Email { get; set; }
public bool IsEmailAuthenticationGuestUser { get; set; }
public bool IsShareByEmailGuestUser { get; set; }
public bool IsSiteAdmin { get; set; }
public UserIdDetails UserId { get; set; }
}
You can do that easily with a projection.
var title = values.Where(v => v.Id == 37).Select(v => v.Title).FirstOrDefault();
var title = values.FirstOrDefault(v => v.Id == 37)?.Title;

C# Json arrary reading

how to read json { "empdata": { "emp": [ { "DATE": "07.01.2021", "EMP_ID": "A001", "S_DATE": "2021-01-07T00:00:00.000+00:00", "Desig": "Engg" }, { "DATE": "08.01.2021", "EMP_ID": "A002", "S_DATE": "2021-01-07T00:00:00.000+00:00", "Desig": "Engg" } ] } } in c#
//Create Class First
public class Emp {
public string DATE { get; set; }
public string EMP_ID { get; set; }
public DateTime S_DATE { get; set; }
public string Desig { get; set; }
}
public class Empdata {
public List<Emp> emp { get; set; }
}
public class Data{
public Empdata empdata { get; set; }
}
string JsonResponse="Your Json Data";
Data JsonData= JsonConvert.DeserializeObject(JsonResponse);
JsonData Will Have all of Ur Data

Json array problem.. i need really help --- .net core mvc

These are my classes
<pre>///Thank you for helping me....
public class Sport
{
public string id { get; set; }
public string name { get; set; }
}
public class Category
{
public string id { get; set; }
public string name { get; set; }
public string country_code { get; set; }
}
public class Competition
{
public string id { get; set; }
public string name { get; set; }
}
public class Season
{
public string id { get; set; }
public string name { get; set; }
public string start_date { get; set; }
public string end_date { get; set; }
public string year { get; set; }
public string competition_id { get; set; }
}
public class Stage
{
public int order { get; set; }
public string type { get; set; }
public string phase { get; set; }
public string start_date { get; set; }
public string end_date { get; set; }
public string year { get; set; }
}
public class Round
{
public int number { get; set; }
public string other_sport_event_id { get; set; }
public int cup_round_sport_event_number { get; set; }
public int cup_round_number_of_sport_events { get; set; }
}
public class Group
{
public string id { get; set; }
public string name { get; set; }
}
public class SportEventContext
{
public Sport sport { get; set; }
public Category category { get; set; }
public Competition competition { get; set; }
public Season season { get; set; }
public Stage stage { get; set; }
public Round round { get; set; }
public IList<Group> groups { get; set; }
}
public class SportEventProperties
{
public bool lineups { get; set; }
public bool extended_player_stats { get; set; }
public bool extended_team_stats { get; set; }
public bool ballspotting { get; set; }
public bool commentary { get; set; }
public bool fun_facts { get; set; }
public bool goal_scorers { get; set; }
public string scores { get; set; }
public bool game_clock { get; set; }
public bool deeper_play_by_play { get; set; }
public bool deeper_player_stats { get; set; }
public bool deeper_team_stats { get; set; }
public bool basic_play_by_play { get; set; }
public bool basic_player_stats { get; set; }
public bool basic_team_stats { get; set; }
public string lineups_availability { get; set; }
}
public class Coverage
{
public string type { get; set; }
public SportEventProperties sport_event_properties { get; set; }
}
public class Competitor
{
public string id { get; set; }
public string name { get; set; }
public string country { get; set; }
public string country_code { get; set; }
public string abbreviation { get; set; }
public string qualifier { get; set; }
public string gender { get; set; }
public Statistics statistics { get; set; }
}
public class Ground
{
public bool neutral { get; set; }
}
public class Referee
{
public string id { get; set; }
public string name { get; set; }
public string nationality { get; set; }
public string country_code { get; set; }
public string type { get; set; }
}
public class SportEventConditions
{
public Ground ground { get; set; }
public IList<Referee> referees { get; set; }
}
public class Venue
{
public string id { get; set; }
public string name { get; set; }
public int capacity { get; set; }
public string city_name { get; set; }
public string country_name { get; set; }
public string map_coordinates { get; set; }
public string country_code { get; set; }
}
public class SportEvent
{
public string id { get; set; }
public DateTime start_time { get; set; }
public bool start_time_confirmed { get; set; }
public SportEventContext sport_event_context { get; set; }
public Coverage coverage { get; set; }
public IList<Competitor> competitors { get; set; }
public SportEventConditions sport_event_conditions { get; set; }
public Venue venue { get; set; }
}
public class PeriodScore
{
public int home_score { get; set; }
public int away_score { get; set; }
public string type { get; set; }
public int number { get; set; }
}
public class Clock
{
public string played { get; set; }
}
public class SportEventStatus
{
public string status { get; set; }
public string match_status { get; set; }
public int home_score { get; set; }
public int away_score { get; set; }
public IList<PeriodScore> period_scores { get; set; }
public Clock clock { get; set; }
}
public class Statistics
{
public int yellow_cards { get; set; }
public int yellow_red_cards { get; set; }
public int red_cards { get; set; }
public int corner_kicks { get; set; }
public int shots_total { get; set; }
public int shots_on_target { get; set; }
public int shots_off_target { get; set; }
public int shots_blocked { get; set; }
public int ball_possession { get; set; }
public int free_kicks { get; set; }
public int offsides { get; set; }
public int goal_kicks { get; set; }
public int throw_ins { get; set; }
public int shots_saved { get; set; }
public int fouls { get; set; }
public int injuries { get; set; }
public int cards_given { get; set; }
public int substitutions { get; set; }
}
public class Totals
{
public IList<Competitor> competitors { get; set; }
}
public class Summary
{
public SportEvent sport_event { get; set; }
public SportEventStatus sport_event_status { get; set; }
public Statistics statistics { get; set; }
}
public class SoccerInformation
{
public DateTime generated_at { get; set; }
public IList<Summary> summaries { get; set; }
}
</pre>
And the some of the json data
<pre>
"summaries": [
{
"sport_event": {
"id": "sr:sport_event:24534090",
"start_time": "2020-11-23T12:00:00+00:00",
"start_time_confirmed": true,
"sport_event_context": {
"sport": {
"id": "sr:sport:1",
"name": "Futbol"
},
"category": {
"id": "sr:category:297",
"name": "Azerbaycan",
"country_code": "AZE"
},
"competition": {
"id": "sr:competition:709",
"name": "Premier Lig"
},
"season": {
"id": "sr:season:77839",
"name": "Premier Lig 20\/21",
"start_date": "2020-08-21",
"end_date": "2021-05-31",
"year": "20\/21",
"competition_id": "sr:competition:709"
},
"stage": {
"order": 1,
"type": "league",
"phase": "regular season",
"start_date": "2020-08-21",
"end_date": "2021-05-31",
"year": "20\/21"
},
"round": {
"number": 10
},
"groups": [
{
"id": "sr:league:51295",
"name": "Premier League 20\/21"
}
]
},
"coverage": {
"type": "sport_event",
"sport_event_properties": {
"lineups": false,
"extended_player_stats": false,
"extended_team_stats": false,
"ballspotting": false,
"commentary": false,
"fun_facts": true,
"goal_scorers": true,
"scores": "live",
"game_clock": true,
"deeper_play_by_play": false,
"deeper_player_stats": false,
"deeper_team_stats": false,
"basic_play_by_play": false,
"basic_player_stats": false,
"basic_team_stats": false
}
},
"competitors": [
{
"id": "sr:competitor:382568",
"name": "Sabah FC",
"country": "Azerbaycan",
"country_code": "AZE",
"abbreviation": "SBH",
"qualifier": "home",
"gender": "male"
},
{
"id": "sr:competitor:281393",
"name": "Sabail FK",
"country": "Azerbaycan",
"country_code": "AZE",
"abbreviation": "SAB",
"qualifier": "away",
"gender": "male"
}
],
"sport_event_conditions": {
"ground": {
"neutral": false
}
}
},
"sport_event_status": {
"status": "closed",
"match_status": "ended",
"home_score": 2,
"away_score": 1,
"winner_id": "sr:competitor:382568",
"period_scores": [
{
"home_score": 2,
"away_score": 0,
"type": "regular_period",
"number": 1
},
{
"home_score": 0,
"away_score": 1,
"type": "regular_period",
"number": 2
}
]
},
"statistics": {
"totals": {
"competitors": [
{
"id": "sr:competitor:382568",
"name": "Sabah FC",
"abbreviation": "SBH",
"qualifier": "home",
"statistics": {
"yellow_cards": 2,
"cards_given": 2,
"substitutions": 3,
"corner_kicks": 3,
"injuries": 1
}
},
{
"id": "sr:competitor:281393",
"name": "Sabail FK",
"abbreviation": "SAB",
"qualifier": "away",
"statistics": {
"yellow_cards": 1,
"cards_given": 1,
"substitutions": 4,
"corner_kicks": 4
}
}
]
}
}
}
</pre>
and i used to json to c# these codes:
<pre>
var content = await result.Content.ReadAsStringAsync();///Thank you for helping me....
return JsonConvert.DeserializeObject<SoccerInformation>(content);///Thank you
im trying to list matches to learn how to get datas from json to .net core mvc
i deserialized json to c# object via using the json2c# website
but i can't reach the some of the classes like
name of the competitors one by one...
first period scores and scond period scores
im trying to do this at the view part of the MVC
i send the model but i can't list them via using Foreach loop in the view.
First verify that your json string adheres to the 'SoccerInformation' class. I don't find a generated_at field in your json.
Secondly, verify that all your json Keys are same as your class property names.
Thirdly, try accessing these with JObject.

Serialize multiples Models classes/View models into a single Json

I'm using asp.Net Core (EF/MVC) and consuming an API through httpRequestMessage StringContent.
How can I do for serialize multiples Models classes/View models into a single Json (Newtonsoft.Json), like the exemple below?
I will really appreciate some code exemple or anything else...
{
"seller_id": "6eb2412c-165a-41cd-b1d9-76c575d70a28",
"amount": 100,
"order": {
"order_id": "6d2e4380-d8a3-4ccb-9138-c289182818a3",
"product_type": "service"
},
"customer": {
"customer_id": "customer_21081826",
"email": "customer#email.com.br",
"billing_address": {
"street": "Av. Brasil",
"number": "1000",
"city": "Porto Alegre",
"state": "RS",
"postal_code": "90230060"
}
},
"device": {
"ip_address": "127.0.0.1",
"device_id": "hash-device-id"
}
}
Create models like below:
public class RootoClass
{
public Guid Seller_id { get; set; }
public int Amount { get; set; }
public Order Order { get; set; }
public Customer Customer { get; set; }
public Device Device { get; set; }
}
public class Order
{
public Guid Order_id { get; set; }
public string Product_type { get; set; }
}
public class Customer
{
public string Customer_id { get; set; }
public string Email { get; set; }
public Billing_Address Billing_address { get; set; }
}
public class Billing_Address
{
public string Street { get; set; }
public string Number { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Postal_code { get; set; }
}
public class Device
{
public string Ip_address { get; set; }
public string Device_id { get; set; }
}
Using Newtonsoft.Json.JsonConvert:
public string Index()
{
var model = new RootoClass()
{
Seller_id = new Guid("6eb2412c-165a-41cd-b1d9-76c575d70a28"),
Amount = 100,
Order = new Order()
{
Order_id = new Guid("6d2e4380-d8a3-4ccb-9138-c289182818a3"),
Product_type = "service"
},
Customer = new Customer()
{
Customer_id = "customer_21081826",
Email = "customer#email.com.br",
Billing_address = new Billing_Address()
{
Street = "Brasil",
Number = "1000",
City = "Porto Alegre",
State = "RS",
Postal_code= "90230060"
}
},
Device = new Device()
{
Ip_address= "127.0.0.1",
Device_id= "hash-device-id"
}
};
var json = JsonConvert.SerializeObject(model);
return json;
}

google book api deserialize jsonconvert returning null

i am trying to deserealize json as `JsonConvert.DeserializeObject(responseBodyAsText) object. the problem is that i am not able to return anything in it. how can i populate the classes i generated below from json and in which order?. do i need to call them in order?
httpClient = new HttpClient();
httpClient.MaxResponseContentBufferSize = 256000;
httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
string responseBodyAsText;
HttpResponseMessage response = await httpClient.GetAsync("https://www.googleapis.com/books/v1/volumes?q=harry+potter");
response.EnsureSuccessStatusCode();
responseBodyAsText = await response.Content.ReadAsStringAsync();
responseBodyAsText = responseBodyAsText.Replace("<br>", Environment.NewLine); // Insert new lines
var jarray = JsonConvert.DeserializeObject<VolumeInfo>(responseBodyAsText);
this is my google books api json return
{
"kind": "books#volumes",
"totalItems": 884,
"items": [
{
"kind": "books#volume",
"id": "jk87_y-ubE0C",
"etag": "Bv3tg9bC2Kk",
"selfLink": "https://www.googlea",
"volumeInfo": {
"title": "Harry Potter a",
"authors": [
"J.K. Rowling"
],
"publisher": "Pottermore",
"publishedDate": "2012-03-27",
"description": "Harry Potter ",
"industryIdentifiers": [
{
"type": "ISBN_10",
"identifier": "1781100047"
}
],
"printType": "BOOK",
"categories": [
"Juvenile Fiction"
],
"averageRating": 4.0,
"ratingsCount": 3560,
"contentVersion": "0.1.1.0.preview.2",
"imageLinks":
{
"smallThumbnail": "http://bks5.",
"thumbnail": "http://bks5.book"
},
"language": "en",
"previewLink": "http:",
"infoLink": "http://b",
"canonicalVolumeLink": "http:"
},
"saleInfo": {
"country": "PK",
"saleability": "NOT_FOR_SALE",
"isEbook": false
},
"accessInfo": {
"country": "PK",
"viewability": "NO_PAGES",
"embeddable": false,
"publicDomain": false,
"textToSpeechPermission": "ALLOWED",
"epub": {
"isAvailable": true
},
"pdf": {
"isAvailable": true
},
"webReaderLink": "http://books.google.com/books/reader?id=jk87_y-ubE0C&hl=&printsec=frontcover&output=reader&source=gbs_api",
"accessViewStatus": "NONE"
},
"searchInfo": {
"textSnippet": "Harry Potter is due to start his fifth year at Hogwarts School of Witchcraft and Wizardry."
}
}
]
}
this are my classes . i hope i have generated them correctly
public class IndustryIdentifier
{
public string type { get; set; }
public string identifier { get; set; }
}
public class ImageLinks
{
public string smallThumbnail { get; set; }
public string thumbnail { get; set; }
}
public class VolumeInfo
{
public string title { get; set; }
public List<string> authors { get; set; }
public string publisher { get; set; }
public string publishedDate { get; set; }
public string description { get; set; }
public List<IndustryIdentifier> industryIdentifiers { get; set; }
public string printType { get; set; }
public List<string> categories { get; set; }
public double averageRating { get; set; }
public int ratingsCount { get; set; }
public string contentVersion { get; set; }
public ImageLinks imageLinks { get; set; }
public string language { get; set; }
public string previewLink { get; set; }
public string infoLink { get; set; }
public string canonicalVolumeLink { get; set; }
}
public class SaleInfo
{
public string country { get; set; }
public string saleability { get; set; }
public bool isEbook { get; set; }
}
public class Epub
{
public bool isAvailable { get; set; }
}
public class Pdf
{
public bool isAvailable { get; set; }
}
public class AccessInfo
{
public string country { get; set; }
public string viewability { get; set; }
public bool embeddable { get; set; }
public bool publicDomain { get; set; }
public string textToSpeechPermission { get; set; }
public Epub epub { get; set; }
public Pdf pdf { get; set; }
public string webReaderLink { get; set; }
public string accessViewStatus { get; set; }
}
public class SearchInfo
{
public string textSnippet { get; set; }
}
public class Item
{
public string kind { get; set; }
public string id { get; set; }
public string etag { get; set; }
public string selfLink { get; set; }
public VolumeInfo volumeInfo { get; set; }
public SaleInfo saleInfo { get; set; }
public AccessInfo accessInfo { get; set; }
public SearchInfo searchInfo { get; set; }
}
public class RootObject
{
public string kind { get; set; }
public int totalItems { get; set; }
public List<Item> items { get; set; }
}
You need to convert your json to RootObject and not to VolumeInfo, so this line:
var jarray = JsonConvert.DeserializeObject<VolumeInfo>(responseBodyAsText);
Becomes this line:
var jarray = JsonConvert.DeserializeObject<RootObject>(responseBodyAsText);
Use http://jsonclassgenerator.codeplex.com/ to generate the classes for the JSON you receive.
Then use var obj = JsonConvert.Deseiralize(responseBodyAsText);. I have tested this and it works perfectly.