I have a variable result which contains a JSON object:
result = JsonConvert.DeserializeObject<PullRequestModel>(responseData);
I would like to use for loop over result as:
#for (var key = 0; key < result.value.length; key++)
{
}
But C# thinks .length is part of the PullRequestModel, and the code is not working.
How do I get around this problem?
This is the PullRequestModel
namespace TestApp.Model.PullRequestModel
{
public class Avatar
{
public string href { get; set; }
}
public class CompletionOptions
{
public string mergeCommitMessage { get; set; }
public bool deleteSourceBranch { get; set; }
public bool squashMerge { get; set; }
public string mergeStrategy { get; set; }
public bool triggeredByAutoComplete { get; set; }
public List<object> autoCompleteIgnoreConfigIds { get; set; }
}
public class CreatedBy
{
public string displayName { get; set; }
public string url { get; set; }
public Links _links { get; set; }
public string id { get; set; }
public string uniqueName { get; set; }
public string imageUrl { get; set; }
public string descriptor { get; set; }
public string href { get; set; }
}
public class Iterations
{
public string href { get; set; }
}
public class LastMergeCommit
{
public string commitId { get; set; }
public string url { get; set; }
}
public class LastMergeSourceCommit
{
public string commitId { get; set; }
public string url { get; set; }
}
public class LastMergeTargetCommit
{
public string commitId { get; set; }
public string url { get; set; }
}
public class Links
{
public Avatar avatar { get; set; }
public Self self { get; set; }
public Repository repository { get; set; }
public WorkItems workItems { get; set; }
public SourceBranch sourceBranch { get; set; }
public TargetBranch targetBranch { get; set; }
public Statuses statuses { get; set; }
public SourceCommit sourceCommit { get; set; }
public TargetCommit targetCommit { get; set; }
public MergeCommit mergeCommit { get; set; }
public CreatedBy createdBy { get; set; }
public Iterations iterations { get; set; }
}
public class MergeCommit
{
public string href { get; set; }
}
public class Project
{
public string id { get; set; }
public string name { get; set; }
public string state { get; set; }
public string visibility { get; set; }
public DateTime lastUpdateTime { get; set; }
}
public class Repository
{
public string id { get; set; }
public string name { get; set; }
public string url { get; set; }
public Project project { get; set; }
public string href { get; set; }
}
public class Reviewer
{
public string reviewerUrl { get; set; }
public int vote { get; set; }
public bool hasDeclined { get; set; }
public bool isRequired { get; set; }
public bool isFlagged { get; set; }
public string displayName { get; set; }
public string url { get; set; }
public Links _links { get; set; }
public string id { get; set; }
public string uniqueName { get; set; }
public string imageUrl { get; set; }
public bool isContainer { get; set; }
public List<VotedFor> votedFor { get; set; }
}
public class PullRequestModel
{
public List<Value> value { get; set; }
public int count { get; set; }
}
public class Self
{
public string href { get; set; }
}
public class SourceBranch
{
public string href { get; set; }
}
public class SourceCommit
{
public string href { get; set; }
}
public class Statuses
{
public string href { get; set; }
}
public class TargetBranch
{
public string href { get; set; }
}
public class TargetCommit
{
public string href { get; set; }
}
public class Value
{
public Repository repository { get; set; }
public int pullRequestId { get; set; }
public int codeReviewId { get; set; }
public string status { get; set; }
public CreatedBy createdBy { get; set; }
public DateTime creationDate { get; set; }
public DateTime closedDate { get; set; }
public string title { get; set; }
public string description { get; set; }
public string sourceRefName { get; set; }
public string targetRefName { get; set; }
public string mergeStatus { get; set; }
public bool isDraft { get; set; }
public string mergeId { get; set; }
public LastMergeSourceCommit lastMergeSourceCommit { get; set; }
public LastMergeTargetCommit lastMergeTargetCommit { get; set; }
public LastMergeCommit lastMergeCommit { get; set; }
public List<Reviewer> reviewers { get; set; }
public List<object> labels { get; set; }
public string url { get; set; }
public Links _links { get; set; }
public CompletionOptions completionOptions { get; set; }
public bool supportsIterations { get; set; }
public DateTime completionQueueTime { get; set; }
}
public class VotedFor
{
public string reviewerUrl { get; set; }
public int vote { get; set; }
public string displayName { get; set; }
public string url { get; set; }
public Links _links { get; set; }
public string id { get; set; }
public string uniqueName { get; set; }
public string imageUrl { get; set; }
public bool isContainer { get; set; }
}
public class WorkItems
{
public string href { get; set; }
}
}
This is the cause of the whole problem, if anyone is curious:
#if(result == null)
{
<p> No pull requests found</p>
}
else
{
#foreach (var item in result.value)
{
<div class="accordion">
<input type="checkbox" id="tab1">
<label class="accordion-label" for="tab1"> #item.title </label>
<div class="accordion-content">
<WorkItems PersonalAccessToken="#PersonalAccessToken" WorkItemUrl="#item._links.workItems.href"></WorkItems>
</div>
</div>
}
}
The above code works (it's a Blazor app) I loop trough all Pull requests and show associated Work Items for the PR.
But In order to crete a simple accordion, the I must increment id="tab1"> because in each loop, so my idea was to ditch #foreach and use #for loop, so I can make use of the key to increment the value of id="tab1">
Hope it makes sense
result = JsonConvert.DeserializeObject<PullRequestModel>(responseData);
#for (var key = 0; key < result.value.Count; key++)
{
}
List<> exposes the Count property not Length property.
It would appear you are deserializing a single object and not an enumerable type. Please try using the following if you want to return something to loop through:
result = JsonConvert.DeserializeObject<List<PullRequestModel>>(responseData);
#for (var key = 0; key < result.Count; key++)
{
}
Count is a property of of the List object in this case.
Related
I'm looking for a C# object that matches the sample payload of the build.complete event found at https://learn.microsoft.com/en-us/azure/devops/service-hooks/events?view=vsts#build.complete. The reference page recommends a nuget package but I can't find a "BuildCompleteEvent" in it.
I am looking for this object because I have a TFS service hook outputting to an Azure Storage Queue, and when I read that message off the queue in an Azure Function I want to be able to parse the message string as a useful C# object.
For "Build completed" event:
public class Message
{
public string text { get; set; }
public string html { get; set; }
public string markdown { get; set; }
}
public class DetailedMessage
{
public string text { get; set; }
public string html { get; set; }
public string markdown { get; set; }
}
public class Drop
{
public string location { get; set; }
public string type { get; set; }
public string url { get; set; }
public string downloadUrl { get; set; }
}
public class Log
{
public string type { get; set; }
public string url { get; set; }
public string downloadUrl { get; set; }
}
public class LastChangedBy
{
public string id { get; set; }
public string displayName { get; set; }
public string uniqueName { get; set; }
public string url { get; set; }
public string imageUrl { get; set; }
}
public class Definition
{
public int batchSize { get; set; }
public string triggerType { get; set; }
public string definitionType { get; set; }
public int id { get; set; }
public string name { get; set; }
public string url { get; set; }
}
public class Queue
{
public string queueType { get; set; }
public int id { get; set; }
public string name { get; set; }
public string url { get; set; }
}
public class RequestedFor
{
public string id { get; set; }
public string displayName { get; set; }
public string uniqueName { get; set; }
public string url { get; set; }
public string imageUrl { get; set; }
}
public class Request
{
public int id { get; set; }
public string url { get; set; }
public RequestedFor requestedFor { get; set; }
}
public class Resource
{
public string uri { get; set; }
public int id { get; set; }
public string buildNumber { get; set; }
public string url { get; set; }
public DateTime startTime { get; set; }
public DateTime finishTime { get; set; }
public string reason { get; set; }
public string status { get; set; }
public string dropLocation { get; set; }
public Drop drop { get; set; }
public Log log { get; set; }
public string sourceGetVersion { get; set; }
public LastChangedBy lastChangedBy { get; set; }
public bool retainIndefinitely { get; set; }
public bool hasDiagnostics { get; set; }
public Definition definition { get; set; }
public Queue queue { get; set; }
public List<Request> requests { get; set; }
}
public class Collection
{
public string id { get; set; }
}
public class Account
{
public string id { get; set; }
}
public class Project
{
public string id { get; set; }
}
public class ResourceContainers
{
public Collection collection { get; set; }
public Account account { get; set; }
public Project project { get; set; }
}
public class RootObject
{
public string id { get; set; }
public string eventType { get; set; }
public string publisherId { get; set; }
public string scope { get; set; }
public Message message { get; set; }
public DetailedMessage detailedMessage { get; set; }
public Resource resource { get; set; }
public string resourceVersion { get; set; }
public ResourceContainers resourceContainers { get; set; }
public DateTime createdDate { get; set; }
}
I have built a bot the needs to get user's location as longitude/latitude, it was working perfectly fine in both android and iOS, but right now I can get the location from messenger installed on android device, but cannot achieve that on a messenger installed on iOS device! any help?
Note: am using a c# class that receives the callback from facebook, not the Microsoft Bot Frameworks.
[ActionName("Receive")]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ReceivePost(BotRequest data)
{
Task.Factory.StartNew(() =>
{
foreach (var entry in data.entry)
{
foreach (var message in entry.messaging)
{
foreach (var item in message.message.attachments)
{
if (item.payload != null)
{
// here i can get the location
// if the location sent from android I can get attachment with long/lat
// if location sent from iOS I get attachment as null
var location = item.payload.coordinates;
}
}
}
}
});
return new HttpStatusCodeResult(HttpStatusCode.OK);}
BotRequest class:
using Newtonsoft.Json;
using System.Collections.Generic;
public class BotRequest
{
public string #object { get; set; }
public List<BotEntry> entry { get; set; }
}
public class BotEntry
{
public string id { get; set; }
public long time { get; set; }
public List<BotMessageReceivedRequest> messaging { get; set; }
}
public class FBUser
{
public string first_name { get; set; }
public string last_name { get; set; }
public string profile_pic { get; set; }
public string locale { get; set; }
public int timezone { get; set; }
public string gender { get; set; }
}
public class BotMessageReceivedRequest
{
public BotUser sender { get; set; }
public BotUser recipient { get; set; }
public string timestamp { get; set; }
public BotMessage message { get; set; }
public BotPostback postback { get; set; }
}
public class BotPostback
{
public string payload { get; set; }
}
public class BotMessageResponse
{
public BotUser recipient { get; set; }
public MessageResponse message { get; set; }
}
public class BotMessage
{
public string mid { get; set; }
public List<MessageAttachment> attachments { get; set; }
public long seq { get; set; }
public string text { get; set; }
public QuickReply quick_reply { get; set; }
}
public class BotUser
{
public string id { get; set; }
}
public class MessageResponse
{
public dynamic attachment { get; set; }
public List<QuickReply> quick_replies { get; set; }
public string text { get; set; }
}
public class QuickReply
{
public string content_type { get; set; }
public string title { get; set; }
public string payload { get; set; }
}
public class ResponseButtons
{
public string type { get; set; }
public string title { get; set; }
public string payload { get; set; }
public string url { get; set; }
public string webview_height_ratio { get; set; }
}
public class MessageAttachment
{
public string type { get; set; }
public MessageAttachmentPayLoad payload { get; set; }
}
public class MessageAttachmentPayLoad
{
public string url { get; set; }
public string template_type { get; set; }
public string top_element_style { get; set; }
public List<PayloadElements> elements { get; set; }
public List<ResponseButtons> buttons { get; set; }
public string recipient_name { get; set; }
public string order_number { get; set; }
public string currency { get; set; }
public string payment_method { get; set; }
public string order_url { get; set; }
public string timestamp { get; set; }
public Address address { get; set; }
public Summary summary { get; set; }
public coordinates coordinates { get; set; }
}
public class coordinates
{
public string lat { get; set; }
public string #long { get; set; }
}
public class PayloadElements
{
public string title { get; set; }
public string image_url { get; set; }
public string subtitle { get; set; }
public List<ResponseButtons> buttons { get; set; }
public string item_url { get; set; }
public int? quantity { get; set; }
public decimal? price { get; set; }
public string currency { get; set; }
}
public class Address
{
internal string street_2;
public string street_1 { get; set; }
public string city { get; set; }
public string postal_code { get; set; }
public string country { get; set; }
public string state { get; set; }
}
public class Summary
{
public decimal? subtotal { get; set; }
public decimal? shipping_cost { get; set; }
public decimal? total_tax { get; set; }
public decimal total_cost { get; set; }
}
Through webrequest I am getting response text which is in Json I use Newtonsoft.Json to parse. I created classes with the help of examples from stackoverflow website but couldn't figure out how to loop whole response into an array or datatable/dataview.
JsonSerializer serializer = new JsonSerializer();
public class Link
{
public string rel { get; set; }
public string href { get; set; }
}
public class Naeringskode1
{
public string kode { get; set; }
public string beskrivelse { get; set; }
}
public class Postadresse
{
public string adresse { get; set; }
public string postnummer { get; set; }
public string poststed { get; set; }
public string kommunenummer { get; set; }
public string kommune { get; set; }
public string landkode { get; set; }
public string land { get; set; }
}
public class Beliggenhetsadresse
{
public string adresse { get; set; }
public string postnummer { get; set; }
public string poststed { get; set; }
public string kommunenummer { get; set; }
public string kommune { get; set; }
public string landkode { get; set; }
public string land { get; set; }
}
public class Link2
{
public string rel { get; set; }
public string href { get; set; }
}
public class Naeringskode2
{
public string kode { get; set; }
public string beskrivelse { get; set; }
}
public class Datum
{
public int organisasjonsnummer { get; set; }
public string navn { get; set; }
public string organisasjonsform { get; set; }
public string registreringsdatoEnhetsregisteret { get; set; }
public string registrertIMvaregisteret { get; set; }
public int antallAnsatte { get; set; }
public Naeringskode1 naeringskode1 { get; set; }
public Postadresse postadresse { get; set; }
public Beliggenhetsadresse beliggenhetsadresse { get; set; }
public int overordnetEnhet { get; set; }
public List<Link2> links { get; set; }
public string hjemmeside { get; set; }
public Naeringskode2 naeringskode2 { get; set; }
}
public class Page
{
public int size { get; set; }
public int page { get; set; }
}
public class RootObject
{
public List<Link> links { get; set; }
public List<Datum> data { get; set; }
public Page page { get; set; }
}
I have this json
and i want to deserialize it so I can get each object's value for example:
"icon_url": "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpouLWzKjhzw8zFdC5K092kl5SClMj3PLXFhGpC_Pp8j-3I4IG7i1Hn_UI-Nmj3ItDGe1BoN1mCr1G4xL_vhMS8tcmcn3JhuihwsHvbzQv3309k3tBw8A",
The problem is I can make the class(es) that I need so I can deserialize the json because the json string has nested objects.
I used json2csharp to help me generate classes. After some merging and cleaning up, this is what I got:
public class InventoryItem
{
public string id { get; set; }
public string classid { get; set; }
public string instanceid { get; set; }
public string amount { get; set; }
public int pos { get; set; }
}
public class AppData
{
public string def_index { get; set; }
public int? is_itemset_name { get; set; }
public int? limited { get; set; }
}
public class Description
{
public string type { get; set; }
public string value { get; set; }
public string color { get; set; }
public AppData app_data { get; set; }
}
public class Action
{
public string name { get; set; }
public string link { get; set; }
}
public class Tag
{
public string internal_name { get; set; }
public string name { get; set; }
public string category { get; set; }
public string category_name { get; set; }
public string color { get; set; }
}
public class RgDescription
{
public string appid { get; set; }
public string classid { get; set; }
public string instanceid { get; set; }
public string icon_url { get; set; }
public string icon_url_large { get; set; }
public string icon_drag_url { get; set; }
public string name { get; set; }
public string market_hash_name { get; set; }
public string market_name { get; set; }
public string name_color { get; set; }
public string background_color { get; set; }
public string type { get; set; }
public int tradable { get; set; }
public int marketable { get; set; }
public int commodity { get; set; }
public string market_tradable_restriction { get; set; }
public List<Description> descriptions { get; set; }
public List<Action> actions { get; set; }
public List<Action> market_actions { get; set; }
public List<Tag> tags { get; set; }
}
public class RootObject
{
public bool success { get; set; }
public IDictionary<string, InventoryItem> rgInventory { get; set; }
public List<object> rgCurrency { get; set; }
public IDictionary<string, RgDescription> rgDescriptions { get; set; }
public bool more { get; set; }
public bool more_start { get; set; }
}
These appear to work correctly, you can deserialize and serialize with code like this:
var obj = JsonConvert.DeserializeObject<RootObject>(oldString);
Console.WriteLine(obj.rgDescriptions["310776560_302028390"].icon_url); // e.g.
var newString = JsonConvert.SerializeObject(obj,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
// null value handling is optional, the above makes it a little more like the source string
I am trying to parse JSON response so I created some classes.
Actually I want Leg and Flight class element value. I am trying to get those element value from RootObject but I don't know how to do this. I googled but I am little bit confuse.
I paste my JSON respose , Classes !!
JSON Response :
http://pastebin.com/fjjLxkd2
Classes :
public class Detail
{
}
public class Airport
{
public string kind { get; set; }
public string code { get; set; }
public string city { get; set; }
public string name { get; set; }
}
public class City
{
public string kind { get; set; }
public string code { get; set; }
public string name { get; set; }
}
public class Aircraft
{
public string kind { get; set; }
public string code { get; set; }
public string name { get; set; }
}
public class Tax
{
public string kind { get; set; }
public string id { get; set; }
public string name { get; set; }
}
public class Carrier
{
public string kind { get; set; }
public string code { get; set; }
public string name { get; set; }
}
public class Data
{
public string kind { get; set; }
public List<Airport> airport { get; set; }
public List<City> city { get; set; }
public List<Aircraft> aircraft { get; set; }
public List<Tax> tax { get; set; }
public List<Carrier> carrier { get; set; }
}
public class Flight
{
public string carrier { get; set; }
public string number { get; set; }
}
public class Leg
{
public string kind { get; set; }
public string id { get; set; }
public string aircraft { get; set; }
public string arrivalTime { get; set; }
public string departureTime { get; set; }
public string origin { get; set; }
public string destination { get; set; }
public string originTerminal { get; set; }
public int duration { get; set; }
public int onTimePerformance { get; set; }
public int mileage { get; set; }
public string meal { get; set; }
public bool secure { get; set; }
public string destinationTerminal { get; set; }
public string operatingDisclosure { get; set; }
}
public class Segment
{
public string kind { get; set; }
public int duration { get; set; }
public Flight flight { get; set; }
public string id { get; set; }
public string cabin { get; set; }
public string bookingCode { get; set; }
public int bookingCodeCount { get; set; }
public string marriedSegmentGroup { get; set; }
public List<Leg> leg { get; set; }
public int connectionDuration { get; set; }
}
public class Slouse
{
public string kind { get; set; }
public int duration { get; set; }
public List<Segment> segment { get; set; }
}
public class Fare
{
public string kind { get; set; }
public string id { get; set; }
public string carrier { get; set; }
public string origin { get; set; }
public string destination { get; set; }
public string basisCode { get; set; }
}
public class BagDescriptor
{
public string kind { get; set; }
public string commercialName { get; set; }
public int count { get; set; }
public string subcode { get; set; }
public List<string> description { get; set; }
}
public class FreeBaggageOption
{
public string kind { get; set; }
public List<BagDescriptor> bagDescriptor { get; set; }
public int pieces { get; set; }
}
public class SegmentPricing
{
public string kind { get; set; }
public string fareId { get; set; }
public string segmentId { get; set; }
public List<FreeBaggageOption> freeBaggageOption { get; set; }
}
public class Passengers
{
public string kind { get; set; }
public int adultCount { get; set; }
}
public class Tax2
{
public string kind { get; set; }
public string id { get; set; }
public string chargeType { get; set; }
public string code { get; set; }
public string country { get; set; }
public string salePrice { get; set; }
}
public class Pricing
{
public string kind { get; set; }
public List<Fare> fare { get; set; }
public List<SegmentPricing> segmentPricing { get; set; }
public string baseFareTotal { get; set; }
public string saleFareTotal { get; set; }
public string saleTaxTotal { get; set; }
public string saleTotal { get; set; }
public Passengers passengers { get; set; }
public List<Tax2> tax { get; set; }
public string fareCalculation { get; set; }
public string latestTicketingTime { get; set; }
public string ptc { get; set; }
}
public class TripOption
{
public string kind { get; set; }
public string saleTotal { get; set; }
public string id { get; set; }
public List<Slouse> slice { get; set; }
public List<Pricing> pricing { get; set; }
}
public class Trips
{
public string kind { get; set; }
public string requestId { get; set; }
public Data data { get; set; }
public List<TripOption> tripOption { get; set; }
}
public class RootObject
{
public string kind { get; set; }
public Trips trips { get; set; }
}
Code :
var obj0 = JsonConvert.DeserializeObject<RootObject>(responsedata);
Here I got only Trip class element . I want the Leg and Flight class element.
If you want to find information for a specific leg, you need to use Linq to traverse the tree. For example, if you just know the leg id, you could do something like this:
var allLegs = obj0.trips.tripOption.SelectMany(to => to.slice.SelectMany(sl => sl.segment.Select(sg => sg.leg)));
var leg = allLegs.FirstOrDefault(l => l.id == "yourId");
The query for retrieving a flight would be similar. You could also filter by tripOption id to get a specific tripOption and then retrieve flights or legs that are associated with it.