FileHelpers3 - recursive object - c#

This object fills just fine
[DelimitedRecord("|")]
public class LvMenuItems
{
public string Sequence { get; set; }
public string DisplayText { get; set; }
public string MenuId { get; set; }
public string PageUrl { get; set; }
public string ControlPanelSequence { get; set; }
}
[DelimitedRecord("|")]
public class LvMenuItems
{
public string Sequence { get; set; }
public string DisplayText { get; set; }
public string MenuId { get; set; }
public string PageUrl { get; set; }
public string ControlPanelSequence { get; set; }
[LVMenuItems]
public LVMenutItems menu items {get; set;}
}
Is it possible to embed a copy of the same structure as an attribute of an object to introduce recurrsion?

I was going about this completely wrong. The correct way it to declare a single object that corresponds to the delimited file and then use that object to fill a second object that handles recursion.

Related

I am getting error while converting json to object

i am trying to convert JSON to object following is my json
{"entity":"event","account_id":"acc_8yTsyb2WJOlcka","event":"payment.captured","contains":["payment"],"payload":{"payment":{"entity":{"id":"pay_AKR45WLH0g1ANu","entity":"payment","amount":100,"currency":"INR","status":"captured","order_id":"order_AKR41LsWIgOAB1","invoice_id":null,"international":false,"method":"netbanking","amount_refunded":0,"refund_status":null,"captured":true,"description":"Admission Fees","card_id":null,"bank":"SBIN","wallet":null,"vpa":null,"email":"xxxxx.xxxx#xxx.xxx","contact":"xxxxx","notes":{"address":"NA","merchant_order_id":"2516"},"fee":2,"tax":0,"error_code":null,"error_description":null,"created_at":1528367383}}},"created_at":1528367384}
and the code I am trying to convert to object is
jsonString = JsonConvert.SerializeObject(documentContents);
RazorPayPayload desJsonString = JsonConvert.DeserializeObject<RazorPayPayload>(jsonString);
and the classes where I want to deserialized
public class RazorPayPayload
{
public string entity { get; set; }
public string account_id { get; set; }
public string events { get; set; }
public List<string> contains { get; set; }
public payments payload { get; set; }
public string created_at { get; set; }
}
public class payments
{
public Entities payment { get; set; }
}
public class notes
{
public string address { get; set; }
public string merchant_order_id { get; set; }
public string source { get; set; }
}
public class Entities
{
public Entity entity { get; set; }
}
public class Entity
{
public string id { get; set; }
public string entity { get; set; }
public string amount { get; set; }
public string currency { get; set; }
public string order_id { get; set; }
public string invoice_id { get; set; }
public string international { get; set; }
public string method { get; set; }
public string amount_refunded { get; set; }
public string refund_status { get; set; }
public string captured { get; set; }
public string description { get; set; }
public string card_id { get; set; }
public string bank { get; set; }
public string wallet { get; set; }
public string vpa { get; set; }
public string email { get; set; }
public string contact { get; set; }
public notes notes { get; set; }
public string fee { get; set; }
public string tax { get; set; }
public string error_code { get; set; }
public string error_description { get; set; }
}
I am getting the error "Error converting value to type 'FeePayr_Razor_Webhook.RazorPayPayload'"
Have you tried changing:
{"entity":"event","account_id":"acc_8yTsyb2WJOlcka","event":
to
{"entity":"event","account_id":"acc_8yTsyb2WJOlcka","events":
That would better match your class definition. Or rename your class field to event.
There is a useful visual studio function for converting a json object to c# classes.
Copy the JSON into the clipboard. (helps if the JSON object properties holds data, to determine the data type)
Go to visual studio and place cursor where you'd like to paste in the c# classes.
click edit => paste special => paste json as classes

REST Api returning different object names for the same object, how to handle with RestSharp?

I'm programming a C# implementation for the Qualtrics API (v 2.5) using RestSharp. When calling the method getUserIds, it returns a list of users in JSON format (see the example output below).
The problem/question I face is that for each user object (the list of objects under Result) it generates a different id, starting with URH_. When using json2csharp it assumes ofcourse that it's always a different class, while in fact it's absolutely the same one as you can see in the output, and as is stated in the documentation of the api. How can I best resolve this - so that I can make a class UserData that I can reuse? Because now I obviously always see these random URH_ prefixed classes in each response.
NOTE: I was thinking I could try to massage the response first, and when I get the response replace each URH_ prefixed object under the root Result object with a "UserData" string - but I feel this is breaking the rules a bit, and thought the community would have a better solution?
Below is the raw JSON output (note that I removed sensitive information):
{"Meta":{"Status":"Success","Debug":""},"Result":{"URH_3wpA9pxGbE0c7Xu":{"DivisionID":null,"UserName":"user.name#domain.com","UserFirstName":"x","UserLastName":"x","UserAccountType":"UT_4SjjZmbPphZGKDq","UserEmail":"x.x#x.x","UserAccountStatus":"Active"},"URH_57vQr8MVXgpcPUo":{"DivisionID":"DV_XXXXXXXX","UserName":"jxxxx#xx.xxx","UserFirstName":"X","UserLastName":"X","UserAccountType":"UT_BRANDADMIN","UserEmail":"xxxx#xxg.xxx","UserAccountStatus":"Active"},"URH_6ujW1EP0QJOUaoI":{"DivisionID":"DV_XXXXXXXYZ","UserName":"x.xckx#xxx.xyz","UserFirstName":"x","UserLastName":"x","UserAccountType":"UT_XXXXXABCD","UserEmail":"c.c#cc.com","UserAccountStatus":"Active"}}}
This is what I get when generating a model using json2csharp:
public class Meta
{
public string Status { get; set; }
public string Debug { get; set; }
}
public class URH3wpA9pxGbE0c7Xu
{
public object DivisionID { get; set; }
public string UserName { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public string UserAccountType { get; set; }
public string UserEmail { get; set; }
public string UserAccountStatus { get; set; }
}
public class URH57vQr8MVXgpcPUo
{
public string DivisionID { get; set; }
public string UserName { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public string UserAccountType { get; set; }
public string UserEmail { get; set; }
public string UserAccountStatus { get; set; }
}
public class URH6ujW1EP0QJOUaoI
{
public string DivisionID { get; set; }
public string UserName { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public string UserAccountType { get; set; }
public string UserEmail { get; set; }
public string UserAccountStatus { get; set; }
}
public class Result
{
public URH3wpA9pxGbE0c7Xu URH_3wpA9pxGbE0c7Xu { get; set; }
public URH57vQr8MVXgpcPUo URH_57vQr8MVXgpcPUo { get; set; }
public URH6ujW1EP0QJOUaoI URH_6ujW1EP0QJOUaoI { get; set; }
}
public class RootObject
{
public Meta Meta { get; set; }
public Result Result { get; set; }
}
It's simple - just use Dictionary<string, UserData> generic type for Result field:
public class Response
{
public Meta Meta { get; set; }
public Dictionary<string, UserData> Result { get; set; }
}
public class Meta
{
public string Status { get; set; }
public string Debug { get; set; }
}
public class UserData
{
public string DivisionID { get; set; }
public string UserName { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public string UserAccountType { get; set; }
public string UserEmail { get; set; }
public string UserAccountStatus { get; set; }
}

Parse through deserialized JSON data

I am new to C#. I have successfully consumed the Mailchip API with a simple console app. I am pulling in relevant data and I have successfully used a JSON deserializer on the returned data (Newtonsoft.Json via NuGet). What I need to find is the best way to place the data into variables which I can then pass to a stored procedure to save the data. I know SQL and I know how to pass variables to a stored procedure in C# (connection strings and such).
What I don't know is how to parse through the deserialized data and then place each value into a variable or something I can pass to SQL. I know this is a vague question so here is the current code.
Class MailChimpAPIClient.cs:
//Declare the API Key
public const string APIKey = "My API Key Here";
public static void APIGet(string url)
{
//Syncronious Consumption
var syncClient = new WebClient();
syncClient.Headers.Add(APIKey);
var content = syncClient.DownloadString(url);
//Deseralize the Json String
MailChimpData data = JsonConvert.DeserializeObject<MailChimpData>(content);
}
Class: MailChimpData.cs:
[DataContract]
public class MailChimpData
{
[DataMember]
public List<Unsubscribes> unsubscribes { get; set; }
[DataMember]
public string campaign_id { get; set; }
[DataMember]
public List<Link2> _links { get; set; }
[DataMember]
public int total_items { get; set; }
[DataMember]
public Link link { get; set; }
[DataMember]
public MergeFields mergefields { get; set; }
[DataMember]
public Stats stats { get; set; }
[DataMember]
public Location location { get; set; }
[DataMember]
public List<Member> members { get; set; }
[DataMember]
public string list_id { get; set; }
}
//Unsubscribe Data
public class Link
{
public string rel { get; set; }
public string href { get; set; }
public string method { get; set; }
public string targetSchema { get; set; }
public string schema { get; set; }
}
public class Unsubscribes
{
public string email_id { get; set; }
public string email_address { get; set; }
public string timestamp { get; set; }
public string reason { get; set; }
public string campaign_id { get; set; }
public string list_id { get; set; }
public List<Link> _links { get; set; }
}
public class Link2
{
public string rel { get; set; }
public string href { get; set; }
public string method { get; set; }
public string targetSchema { get; set; }
public string schema { get; set; }
}
//List Data
public class MergeFields
{
public string FNAME { get; set; }
public string LNAME { get; set; }
}
public class Stats
{
public double avg_open_rate { get; set; }
public int avg_click_rate { get; set; }
}
public class Location
{
public double latitude { get; set; }
public double longitude { get; set; }
public int gmtoff { get; set; }
public int dstoff { get; set; }
public string country_code { get; set; }
public string timezone { get; set; }
}
public class Member
{
public string id { get; set; }
public string email_address { get; set; }
public string unique_email_id { get; set; }
public string email_type { get; set; }
public string status { get; set; }
public MergeFields merge_fields { get; set; }
public Stats stats { get; set; }
public string ip_signup { get; set; }
public string timestamp_signup { get; set; }
public string ip_opt { get; set; }
public string timestamp_opt { get; set; }
public int member_rating { get; set; }
public string last_changed { get; set; }
public string language { get; set; }
public bool vip { get; set; }
public string email_client { get; set; }
public Location location { get; set; }
public string list_id { get; set; }
public List<Link> _links { get; set; }
}
Program.cs:
class Program
{
static void Main(string[] args)
{
MailChimpApiClient.APIGet("Custom URL Here");
}
}
So when I run this and look in the Autos window of VS2013 I see this:
members: Count = 4 System.Collections.Generic.List
[0] {MailChimpAPI.Member} MailChimpAPI.Member
_links: Count = 8 System.Collections.Generic.List
email_address: email address here string
email_client: string
email_type: html string
id: (ID Here) string
ip_opt: (IP Here) string
ip_signup: string
language: string
last_changed: 9/16/15 19:31 string
list_id: (List ID Here) string
location: {MailChimpAPI.Location} MailChimpAPI.Location
member_rating: 3 int
merge_fields {MailChimpAPI.MergeFields} MailChimpAPI.MergeFields
stats: {MailChimpAPI.Stats} MailChimpAPI.Stats
status: unsubscribed string
timestamp_opt: 9/16/15 19:26 string
timestamp_signup: string
unique_email_id: (Unique Email ID Here) string
vip: FALSE bool
[1] {MailChimpAPI.Member}: MailChimpAPI.Member
[2] {MailChimpAPI.Member}: MailChimpAPI.Member
[3] {MailChimpAPI.Member}: MailChimpAPI.Member
Raw View
So for each member (0-3), I need to pull each fields value (Field names in bold) into a variable and save it to a database. I just don't know how to parse through each member.
I know this is a long question for a simple C# problem, but if you can remember way back to the beginning of the post I stated "I am new to C#"
Thanks in advance.

Remove a parent based on child values

I have the following data structure
public class Prediction
{
public string Description {get;set;}
public string Id { get; set; }
public List<MatchedSubstring> Matched_substrings { get; set; }
public string Place_id { get; set; }
public string Reference { get; set; }
public List<Term> Terms { get; set; }
public List<string> Types { get; set; }
}
public class GooglePlaceAutocompleteResult
{
public List<Prediction> Predictions { get; set; }
public string Status { get; set; }
}
What I would like to do is remove any items in the Predictions list if their Types collection contains the string "sublocality".
How can I do this with LINQ?
Assuming you are writing a method within GooglePlaceAutocompleteResult, you can write:
Predictions = Predictions.Where(p => !p.Types.Any(t => t.Contains("sublocality")).ToList();
Otherwise the code would be the same but would be result.Predictions = result.Predictions...

Object reference error while reading specific JSON string?

I have used JSON to C# Class Converter and it generates the following Class:
JSON
{"ios_info":{"serialNumber":"F2LLMBNJFFF","imeiNumber":"01388400413235","meid":"","iccID":"8901410427640096045","firstUnbrickDate":"11\/27\/13","lastUnbrickDate":"11\/27\/13","unbricked":"true","unlocked":"false","productVersion":"7.1.2","initialActivationPolicyID":"23","initialActivationPolicyDetails":"US AT&T Puerto Rico and US Virgin Islands Activation Policy","appliedActivationPolicyID":"23","appliedActivationDetails":"US AT&T Puerto Rico and US Virgin Islands Activation Policy","nextTetherPolicyID":"23","nextTetherPolicyDetails":"US AT&T Puerto Rico and US Virgin Islands Activation Policy","macAddress":"ACFDEC6C988A","bluetoothMacAddress":"AC:FD:EC:6C:98:8B","partDescription":"IPHONE 5S SPACE GRAY 64GB-USA"},"fmi":{"#attributes":{"version":"1","deviceCount":"1"},"fmipLockStatusDevice":{"#attributes":{"serial":"F2LLMBNJFFFQ","imei":"013884004132355","isLocked":"true","isLost":"false"}}},"product_info":{"serialNumber":"F2LLMBNJFFF","warrantyStatus":"Apple Limited Warranty","coverageEndDate":"11\/25\/14","coverageStartDate":"11\/26\/13","daysRemaining":"497","estimatedPurchaseDate":"11\/26\/13","purchaseCountry":"United States","registrationDate":"11\/26\/13","imageURL":"http:\/\/service.info.apple.com\/parts\/service_parts\/na.gif","explodedViewURL":"http:\/\/service.info.apple.com\/manuals-ssol.html","manualURL":"http:\/\/service.info.apple.com\/manuals-ssol.html","productDescription":"iPhone 5S","configDescription":"IPHONE 5S GRAY 64GB GSM","slaGroupDescription":"","contractCoverageEndDate":"11\/25\/15","contractCoverageStartDate":"11\/26\/13","contractType":"C1","laborCovered":"Y","limitedWarranty":"Y","partCovered":"Y","notes":"Covered by AppleCare+ - Incidents Available","acPlusFlag":"Y","consumerLawInfo":{"serviceType":"","popMandatory":"","allowedPartType":""}}}
From Above JSON all the data is read but only the line at which i get error is in reading the JSON is:
fmi":{"#attributes":{"version":"1","deviceCount":"1"},"fmipLockStatusDevice":{"#attributes":{"serial":"F2LLMBNJFFFQ","imei":"013884004132355","isLocked":"true","isLost":"false"}}},
Error:
Object Reference not set to an instance of object.
public class AppleAPI
{
public IosInfo ios_info { get; set; }
public ProductInfo product_info { get; set; }
public Fmi fmi { get; set; }
public class IosInfo
{
public string serialNumber { get; set; }
public string imeiNumber { get; set; }
public string meid { get; set; }
public string iccID { get; set; }
public string firstUnbrickDate { get; set; }
public string lastUnbrickDate { get; set; }
public string unbricked { get; set; }
public string unlocked { get; set; }
public string productVersion { get; set; }
public string initialActivationPolicyID { get; set; }
public string initialActivationPolicyDetails { get; set; }
public string appliedActivationPolicyID { get; set; }
public string appliedActivationDetails { get; set; }
public string nextTetherPolicyID { get; set; }
public string nextTetherPolicyDetails { get; set; }
public string macAddress { get; set; }
public string bluetoothMacAddress { get; set; }
public string partDescription { get; set; }
}
public class ConsumerLawInfo
{
public string serviceType { get; set; }
public string popMandatory { get; set; }
public string allowedPartType { get; set; }
}
public class ProductInfo
{
public string serialNumber { get; set; }
public string warrantyStatus { get; set; }
public string coverageEndDate { get; set; }
public string coverageStartDate { get; set; }
public string daysRemaining { get; set; }
public string estimatedPurchaseDate { get; set; }
public string purchaseCountry { get; set; }
public string registrationDate { get; set; }
public string imageURL { get; set; }
public string explodedViewURL { get; set; }
public string manualURL { get; set; }
public string productDescription { get; set; }
public string configDescription { get; set; }
public string slaGroupDescription { get; set; }
public string contractCoverageEndDate { get; set; }
public string contractCoverageStartDate { get; set; }
public string contractType { get; set; }
public string laborCovered { get; set; }
public string limitedWarranty { get; set; }
public string partCovered { get; set; }
public string notes { get; set; }
public string acPlusFlag { get; set; }
public ConsumerLawInfo consumerLawInfo { get; set; }
}
public class Fmi
{
public Attributes invalid_nameattribute { get; set; }
public FmipLockStatusDevice fmipLockStatusDevice { get; set; }
}
public class FmipLockStatusDevice
{
public Attributes2 invalid_nameattribute2 { get; set; }
}
public class Attributes
{
public string version { get; set; }
public string deviceCount { get; set; }
}
public class Attributes2
{
public string serial { get; set; }
public string imei { get; set; }
public string isLocked { get; set; }
public string isLost { get; set; }
}
}
Reading JSON:
string responseText = string.Empty;
AppleAPI appobj = new AppleAPI();
responseText = appobj.VerifyAppleESN(newEsn);
var resobj = JsonConvert.DeserializeObject<AppleAPI>(responseText.Replace("#",string.Empty));
lblSerialNumber.Text = resobj.product_info.serialNumber;
.
.
lblappliedActivationDetails.Text = resobj.ios_info.appliedActivationDetails;
.
.
//getting here error below line: Object ref notset to instance of object
lblfmiVersion.Text = resobj.fmi.invalid_nameattribute.version;
Any Idea?
If you're getting Object Reference not set to an instance of object. that means that you're trying to access properties on an object that is null. Since you said it happens on this line:
lblfmiVersion.Text = resobj.fmi.invalid_nameattribute.version;
that could mean that any of resobj, resobj.fmi, or resobj.fmi.invalid_nameattribute are null. Ignoring the fact that you should have proper null checks in your code to help avoid this situation, let's ask the question, why would any of these objects be null if deserialization succeeded? Perhaps some of the data was not deserialized correctly after all.
When deserializing using Json.Net, it is important to know that if any members of a class do not have matching properties in the JSON, those members will be skipped by Json.Net and thus retain their default values, e.g. null. So one possible reason that you have a null is that the name of a property in your class does not match what is in the JSON.
If we take a look at your Fmi class, one thing that jumps out right away is that it has a suspiciously named property called invalid_nameattribute. In the JSON, there is no such property. Instead, there is a property called #attributes. Your FmipLockStatusDevice class has the same problem. Since they didn't match up, these properties did not get populated during deserialization, so they are null.
So how can we fix this?
This is simple enough: add a [JsonProperty] attribute to your class properties to map them to the right JSON properties. (While you're at it, you might also consider changing the names of those properties in your C# class to something that actually makes sense, like "Attributes".)
public class Fmi
{
[JsonProperty("#attributes")]
public Attributes invalid_nameattribute { get; set; }
public FmipLockStatusDevice fmipLockStatusDevice { get; set; }
}
public class FmipLockStatusDevice
{
[JsonProperty("#attributes")]
public Attributes2 invalid_nameattribute2 { get; set; }
}
OK, now that you have a solution, you should ask yourself, how did you get into this situation in the first place, and how can you avoid it in the future?
You said you used json2csharp.com to generate your classes. You need to be aware that this tool is not foolproof, and will not always be able to generate correct classes to work with your JSON. This is true whenever the JSON property names contain punctuation characters or spaces or start with numbers, because these cannot be turned into valid C# property names. In these cases, json2csharp.com will generate a property name that starts with "invalid". You need to look for these, and make manual adjustments to your classes to fix the issues. Do not just blindly use the generated classes and assume they are correct.
Hope this helps.

Categories

Resources