Null value when mapping from Object.Property to Property with AutoMapper - c#

I want to map Message to MessageDto, so in RoomRead response I will have Collection of MessageDto with Username == User.LastName
public class RoomReadDTO
{
public int Id { get; set; }
public string Name { get; set; }
public bool Type { get; set; }
public ICollection<MessageDTO> Messages { get; set; }
}
public class MessageDTO
{
public int Id { get; set; }
public string Username { get; set; }
public string Content { get; set; }
public DateTime Date { get; set; }
}
public class Message
{
public int Id { get; set; }
public string Content { get; set; }
public DateTime Date { get; set; }
public int UserId { get; set; }
public int RoomId { get; set; }
public User User { get; set; }
public Room Room { get; set; }
}
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Photo { get; set; }
public ICollection<Participants> Participations { get; set; } = new List<Participants>();
public ICollection<Message> Messages { get; set; } = new List<Message>();
}
With this AutoMapper configuration
CreateMap<Message, MessageDTO>()
.ForMember(dest => dest.Username, opt => opt.MapFrom(message => message.User.LastName));
But in response Username property is null
{
"id": 1,
"name": "Private Chat John",
"type": false,
"messages": [
{
"id": 1,
"username": null,
"content": "Hello!",
"date": "2022-12-25T10:30:50"
},
{
"id": 2,
"username": null,
"content": "Hi!",
"date": "2022-12-25T10:32:50"
}
]
}
Can anyone give me some advice?

Related

Deserialize Complex/Branched JSON and accessing branches

I have a JSON response which i generated a model from. the JSON data has various branches with data as shown below.
{
"error": false,
"result": {
"customers": [
{
"district": null,
"feeder": "XXXXXXXXXXX",
"feeder_code": "XXXXXXXXXXX",
"transformer": "XXXXXXXXXXX",
"dss_code": "XXXXXXXXX",
"database_match": "XXXXXXXXXXX",
"accountnumber": "XXXXXXXXXXX",
"meterno": "XXXXXXXXXXX",
"oldaccountnumber": "XXXXXXXXXXX",
"odoo_account_number": "XXXXXXXXXXX",
"customername": "XXXXXXXXXXX",
"address": "XXXXXXXXXXX",
"phone": "",
"tarrif": "XXX",
"tariff_category": "NON-MD",
"service_band": "C ",
"status": "Active",
"status_period": "MAY",
"payment_status": null,
"arrears": "29431.78",
"long_x": "7.0385020000",
"lat_y": "5.4909420000",
"transactional_details": {
"queryresult": {
"responseMessage": "success",
"customer": {
"accountNumber": "XXXXXXXXXXX",
"meterNumber": "XXXXXXXXXXX",
"phoneNumber": "",
"lastName": "XXXXXXXXXXX",
"address": "XXXXXXXXXXX",
"city": "XXXXXXXXXXX",
"district": "Owerri",
"userCategory": "NON-MD",
"customerType": "metered",
"paymentPlan": "Prepaid",
"vat": 0,
"tariffCode": "R2SC-NMD",
"tariffRate": 52.6,
"arrearsBalance": 0,
"billedAmount": 0,
"billedDate": null,
"lastPayDate": "2021-09-21 12:16:46",
"lastpayment": {
"transactionRef": "88099064",
"units": 0,
"transactionDate": "JXXXXXXXXXXX",
"transactionId": "XXXXXXXXXXX",
"transactionBookId": 0,
"amountPaid": 1000,
"mscPaid": 0,
"invoiceNumber": "17289583"
}
},
"responseCode": 200,
"status": "true"
},
"status": true
}
}
],
"row_count": 2
}
}
I have various branches in this JSON response which i need to use. i generated a model class from this JSON as shown below
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class Customer
{
public object district { get; set; }
public string feeder { get; set; }
public string feeder_code { get; set; }
public string transformer { get; set; }
public string dss_code { get; set; }
public string database_match { get; set; }
public string accountnumber { get; set; }
public string meterno { get; set; }
public string oldaccountnumber { get; set; }
public string odoo_account_number { get; set; }
public string customername { get; set; }
public string address { get; set; }
public string phone { get; set; }
public string tarrif { get; set; }
public string tariff_category { get; set; }
public string service_band { get; set; }
public string status { get; set; }
public string status_period { get; set; }
public object payment_status { get; set; }
public string arrears { get; set; }
public string long_x { get; set; }
public string lat_y { get; set; }
public TransactionalDetails transactional_details { get; set; }
}
public class Customer2
{
public string accountNumber { get; set; }
public string meterNumber { get; set; }
public string phoneNumber { get; set; }
public string lastName { get; set; }
public string address { get; set; }
public string city { get; set; }
public string district { get; set; }
public string userCategory { get; set; }
public string customerType { get; set; }
public string paymentPlan { get; set; }
public int vat { get; set; }
public string tariffCode { get; set; }
public double tariffRate { get; set; }
public int arrearsBalance { get; set; }
public int billedAmount { get; set; }
public object billedDate { get; set; }
public string lastPayDate { get; set; }
public Lastpayment lastpayment { get; set; }
}
public class Lastpayment
{
public string transactionRef { get; set; }
public int units { get; set; }
public string transactionDate { get; set; }
public string transactionId { get; set; }
public int transactionBookId { get; set; }
public int amountPaid { get; set; }
public int mscPaid { get; set; }
public string invoiceNumber { get; set; }
}
public class Queryresult
{
public string responseMessage { get; set; }
public Customer customer { get; set; }
public int responseCode { get; set; }
public string status { get; set; }
}
public class Result
{
public ObservableCollection<Customer> customers { get; set; }
public int row_count { get; set; }
}
public class Root
{
public bool error { get; set; }
public Result result { get; set; }
}
public class TransactionalDetails
{
public Queryresult queryresult { get; set; }
public bool status { get; set; }
}
Afterwards i used the C# code to deserialize the JSON as shown below
Root myroot = JsonConvert.DeserializeObject<Root>(readTask);
ObservableCollection<Customer> data = myroot.result.customers;
This works fine, however, i am stuck with just customer Data. I want to be able to get the Transactional details (Customer2) and Lastpayment branches in a collection view. how can i achieve this? Thanks
You can parse your json and read it by linq. ToObject method help you to convert nodes to specific class.
I have taken json text in InputJson variable and then paresed it.
var parsed = JObject.Parse(InputJson);
var innerNodes = JArray.Parse(parsed["result"]["customers"].ToString());
var CustomerList = innerNodes.Select(x => x.ToObject<Customer>()).ToList();
And if you need just some of properties you can use in this way
var CustomerList = innerNodes.Select(x =>
new Customer
{
district = x["district"],
feeder = x["feeder"].ToString(),
transactional_details =x["transactional_details"].ToObject<TransactionalDetails>()
})
.ToList();
If you have different nodes in your object , you can call nodes and check them not be null!
var CustomerList = innerNodes.Select(x => new
{
district = x["district"],
feeder = x["feeder"].ToString(),
transactional_details =x["transactional_details"]?.ToObject<TransactionalDetails>(),
Lastpayment = x["transactional_details"]?["queryresult"]?["customer"]?["lastpayment"]?.ToObject<Lastpayment>(),
billedAmount = x["transactional_details"]?["queryresult"]?["customer"]?["billedAmount"] ?.ToString()
}).ToList();
Customers is an array object so you must iterate through this array.
For example this would work:
Root myroot = JsonConvert.DeserializeObject<Root>(json);
myroot.result.customers.ToList().ForEach(c =>
{
Console.WriteLine(c.transactional_details.queryresult.customer.lastpayment.amountPaid);
});
Looking at Locals in vs debugger for
var customers = myroot.result.customers.ToList();
we get this:
fix Queryresult class by changing Customer to Customer2
public class Queryresult
{
public string responseMessage { get; set; }
public Customer2 customer { get; set; }
public int responseCode { get; set; }
public string status { get; set; }
}
now you can get a lastpayment
Root myroot = JsonConvert.DeserializeObject<Root>(readTask);
LastPayment lastPayment = myroot.result.customers
.Select(c=>c.transactional_details.queryresult.customer.lastpayment).FirstOrDefault();
how to use
var amountPaid = lastPayment.amountPaid; //1000
var invoiceNumber = lastPayment.invoiceNumber; //17289583

Querying Json with Linq, Cannot access child value

I am new to C# with JSON. I would like to select with Nvidia API, the "featuredProduct" part, but I have an error
Cannot access child value on Newtonsoft.Json.Linq.JProperty.
This code works for the "searchedProducts" part.
Can you explain to me why?
const string url = "";
const int refresh = 3000;
string json = getGpuFromNvidia(url);
var jsonParse = JObject.Parse(json);
var result = jsonParse["searchedProducts"]["featuredProduct"]
.Where(n => n["isFounderEdition"].Value<bool>() == true)
.Select(p => new CarteGraphique
{
displayName = (string)p["displayName"],
prdStatus = (string)p["prdStatus"],
directPurchaseLink = (string)p["retailers"][0]["directPurchaseLink"]
})
.ToList();
I tested this code in VS
string json = ...your code
var jsonObj = JsonConvert.DeserializeObject<NvidiaRoot>(json);
var result = jsonObj.searchedProducts.productDetails
.Where(n => n.isFounderEdition)
.Select(p => new
{
displayName = p.displayName,
prdStatus = p.prdStatus,
directPurchaseLink = p.retailers[0].directPurchaseLink
})
.ToList();
OUTPUT
[
{
"displayName": "NVIDIA RTX 3090",
"prdStatus": "out_of_stock",
"directPurchaseLink": "https://www.ldlc.com/fiche/PB89455870.html"
},
{
"displayName": "NVIDIA RTX 3070",
"prdStatus": "out_of_stock",
"directPurchaseLink": "https://www.ldlc.com/fiche/PB74221588.html"
},
{
"displayName": "NVIDIA RTX 3060 Ti",
"prdStatus": "out_of_stock",
"directPurchaseLink": "https://www.ldlc.com/fiche/PB54012144.html"
},
{
"displayName": "NVIDIA RTX 3070 Ti",
"prdStatus": "out_of_stock",
"directPurchaseLink": null
},
{
"displayName": "NVIDIA RTX 3080 Ti",
"prdStatus": "out_of_stock",
"directPurchaseLink": null
}
]
UPDATE
if you need just a feature product
var featuredProduct = jsonObj.searchedProducts.featuredProduct;
var result = new
{
displayName = featuredProduct.displayName,
prdStatus = featuredProduct.prdStatus,
directPurchaseLink = featuredProduct.retailers[0].directPurchaseLink
};
Short OUTPUT
{
"displayName": "NVIDIA RTX 3080",
"prdStatus": "out_of_stock",
"directPurchaseLink": "https://www.ldlc.com/fiche/PB15921567.html"
}
Full OUTPUT
var result = jsonObj.searchedProducts.featuredProduct;
{
"displayName": "NVIDIA RTX 3080",
"totalCount": 1,
"productID": 30045,
"imageURL": "https://assets.nvidia.partners/images/png/nvidia-geforce-rtx-3080.png",
"productTitle": "NVIDIA GEFORCE RTX 3080",
"digitialRiverID": "",
"productSKU": "NVGFT080",
"productUPC": "NVGFT080_FR",
"productUPCOriginal": "NVGFT080",
"productPrice": "€719.00",
"productAvailable": false,
"productRating": null,
"customerReviewCount": null,
"isFounderEdition": true,
"isFeaturedProduct": true,
"certified": false,
"manufacturer": "NVIDIA",
"locale": "FR",
"isFeaturedProdcutFoundInSecondSearch": false,
"category": "GPU",
"gpu": "RTX 3080",
"purchaseOption": "",
"prdStatus": "out_of_stock",
"minShipDays": null,
"maxShipDays": null,
"shipInfo": null,
"isOffer": false,
"offerText": "",
"retailers": [
{
"productId": 30045,
"productTitle": "NVIDIA GEFORCE RTX 3080",
"logoUrl": "https://assets.nvidia.partners/logos/geforce/retailer-ldlc.png",
"isAvailable": true,
"salePrice": "719.00",
"directPurchaseLink": "https://www.ldlc.com/fiche/PB15921567.html",
"purchaseLink": "https://www.ldlc.com/fiche/PB15921567.html",
"hasOffer": false,
"offerText": null,
"partnerId": "45",
"storeId": "45",
"upc": "NVGFT080_FR",
"sku": "NVGFT080",
"stock": 0,
"retailerName": "https://www.ldlc.com",
"type": 80
}
],
"productInfo": [
{
"name": "cooling_system",
"value": "Fan"
},
{
"name": "gpu_boost_clock_speed",
"value": "1.71 GHz"
},
{
"name": "gpu_memory_size",
"value": "10 GB"
}
],
"compareProductInfo": [
{
"name": "cooling_system",
"value": "Fan"
},
{
"name": "gpu_clock_speed",
"value": "1.44 GHz"
},
{
"name": "gpu_boost_clock_speed",
"value": "1.71 GHz"
},
{
"name": "gpu_memory_size",
"value": "10 GB"
}
]
}
classes
public class NvidiaRoot
{
public object categories { get; set; }
public List<Filter> filters { get; set; }
public object filterGroups { get; set; }
public object search { get; set; }
public string version { get; set; }
public List<Sort> sort { get; set; }
public Pagination pagination { get; set; }
public SearchedProducts searchedProducts { get; set; }
public Disclaimer disclaimer { get; set; }
}
public class FilterValue
{
public string dispValue { get; set; }
public object dispValueDesription { get; set; }
public object groupType { get; set; }
public int units { get; set; }
public bool #checked { get; set; }
public object imageURL { get; set; }
public bool isValidate { get; set; }
}
public class Filter
{
public string displayName { get; set; }
public string filterField { get; set; }
public string displayMaxValues { get; set; }
public string fieldType { get; set; }
public int? selectedMinRangeVal { get; set; }
public int? selectedMaxRangeVal { get; set; }
public int? defaultMinRangeVal { get; set; }
public int? defaultMaxRangeVal { get; set; }
public string unitsOfMeasure { get; set; }
public bool #checked { get; set; }
public object units { get; set; }
public List<FilterValue> filterValues { get; set; }
public string dataType { get; set; }
public bool showCount { get; set; }
public int filterDisplayOrder { get; set; }
}
public class Sort
{
public string displayName { get; set; }
public string value { get; set; }
public bool selected { get; set; }
}
public class Pagination
{
public int page { get; set; }
public int limit { get; set; }
public int totalRecords { get; set; }
public bool featuredProductIncludedInCount { get; set; }
}
public class Retailer
{
public int productId { get; set; }
public string productTitle { get; set; }
public string logoUrl { get; set; }
public bool isAvailable { get; set; }
public string salePrice { get; set; }
public string directPurchaseLink { get; set; }
public string purchaseLink { get; set; }
public bool hasOffer { get; set; }
public object offerText { get; set; }
public string partnerId { get; set; }
public string storeId { get; set; }
public string upc { get; set; }
public string sku { get; set; }
public int stock { get; set; }
public string retailerName { get; set; }
public int type { get; set; }
}
public class ProductInfo
{
public string name { get; set; }
public string value { get; set; }
}
public class CompareProductInfo
{
public string name { get; set; }
public string value { get; set; }
}
public class FeaturedProduct
{
public string displayName { get; set; }
public int totalCount { get; set; }
public int productID { get; set; }
public string imageURL { get; set; }
public string productTitle { get; set; }
public string digitialRiverID { get; set; }
public string productSKU { get; set; }
public string productUPC { get; set; }
public string productUPCOriginal { get; set; }
public string productPrice { get; set; }
public bool productAvailable { get; set; }
public object productRating { get; set; }
public object customerReviewCount { get; set; }
public bool isFounderEdition { get; set; }
public bool isFeaturedProduct { get; set; }
public bool certified { get; set; }
public string manufacturer { get; set; }
public string locale { get; set; }
public bool isFeaturedProdcutFoundInSecondSearch { get; set; }
public string category { get; set; }
public string gpu { get; set; }
public string purchaseOption { get; set; }
public string prdStatus { get; set; }
public object minShipDays { get; set; }
public object maxShipDays { get; set; }
public object shipInfo { get; set; }
public bool isOffer { get; set; }
public string offerText { get; set; }
public List<Retailer> retailers { get; set; }
public List<ProductInfo> productInfo { get; set; }
public List<CompareProductInfo> compareProductInfo { get; set; }
}
public class ProductDetail
{
public string displayName { get; set; }
public int totalCount { get; set; }
public int productID { get; set; }
public string imageURL { get; set; }
public string productTitle { get; set; }
public string digitialRiverID { get; set; }
public string productSKU { get; set; }
public string productUPC { get; set; }
public string productUPCOriginal { get; set; }
public string productPrice { get; set; }
public bool productAvailable { get; set; }
public object productRating { get; set; }
public object customerReviewCount { get; set; }
public bool isFounderEdition { get; set; }
public bool isFeaturedProduct { get; set; }
public bool certified { get; set; }
public string manufacturer { get; set; }
public string locale { get; set; }
public bool isFeaturedProdcutFoundInSecondSearch { get; set; }
public string category { get; set; }
public string gpu { get; set; }
public string purchaseOption { get; set; }
public string prdStatus { get; set; }
public object minShipDays { get; set; }
public object maxShipDays { get; set; }
public object shipInfo { get; set; }
public bool isOffer { get; set; }
public string offerText { get; set; }
public List<Retailer> retailers { get; set; }
public List<ProductInfo> productInfo { get; set; }
public List<CompareProductInfo> compareProductInfo { get; set; }
}
public class SearchedProducts
{
public int totalProducts { get; set; }
public bool featuredProductIncludedInCount { get; set; }
public bool featuredProductsFlag { get; set; }
public FeaturedProduct featuredProduct { get; set; }
public List<ProductDetail> productDetails { get; set; }
public List<object> suggestedProductDetails { get; set; }
}
public class Disclaimer
{
public string text { get; set; }
}
You can try the below code.
To get the Featured Product. Sample Working code Here
var jsonParse = JObject.Parse(json);
var featuredProduct = jsonParse["searchedProducts"]["featuredProduct"];
var f = new CarteGraphique
{
displayName = featuredProduct["displayName"].ToString(),
prdStatus = featuredProduct["prdStatus"].ToString(),
directPurchaseLink = featuredProduct["retailers"][0]["directPurchaseLink"].ToString()
};
Console.WriteLine("Featured Product Details : " + f.displayName + ", " + f.prdStatus + ", " + f.directPurchaseLink);

Value from deserialized JSON object is NULL

I am having some trouble getting a value from a deserialized JSON string.
Here is my JSON string:
{
"expand": "names,schema",
"startAt": 0,
"maxResults": 1,
"total": 151,
"issues": [
{
"expand": "operations,versionedRepresentations,editmeta,changelog,renderedFields",
"id": "10210",
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/issue/10210",
"key": "ITSD-202",
"fields": {
"statuscategorychangedate": "2021-01-25T20:12:11.922+0000",
"issuetype": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/issuetype/10003",
"id": "10003",
"description": "For customer support issues. Created by Jira Service Desk.",
"iconUrl": "https://xxxxxxxxxx.atlassian.net/secure/viewavatar?size=medium&avatarId=10308&avatarType=issuetype",
"name": "Support",
"subtask": false,
"avatarId": 10308
},
"timespent": null,
"customfield_10030": null,
"customfield_10031": {
"id": "1",
"name": "Time to resolution",
"_links": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/servicedeskapi/request/10210/sla/1"
},
"completedCycles": [],
"ongoingCycle": {
"startTime": {
"iso8601": "2021-01-25T20:12:11+0000",
"jira": "2021-01-25T20:12:11.592+0000",
"friendly": "Yesterday 08:12",
"epochMillis": 1611605531592
},
"breachTime": {
"iso8601": "2021-02-11T14:30:00+0000",
"jira": "2021-02-11T14:30:00.000+0000",
"friendly": "11/Feb/21 02:30",
"epochMillis": 1613053800000
},
"breached": false,
"paused": false,
"withinCalendarHours": false,
"goalDuration": {
"millis": 432000000,
"friendly": "120h"
},
"elapsedTime": {
"millis": 0,
"friendly": "0m"
},
"remainingTime": {
"millis": 432000000,
"friendly": "120h"
}
}
},
"project": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/project/10000",
"id": "10000",
"key": "ITSD",
"name": "Customer Service Desk",
"projectTypeKey": "service_desk",
"simplified": false,
"avatarUrls": {
"48x48": "https://xxxxxxxxxx.atlassian.net/secure/projectavatar?pid=10000&avatarId=10412",
"24x24": "https://xxxxxxxxxx.atlassian.net/secure/projectavatar?size=small&s=small&pid=10000&avatarId=10412",
"16x16": "https://xxxxxxxxxx.atlassian.net/secure/projectavatar?size=xsmall&s=xsmall&pid=10000&avatarId=10412",
"32x32": "https://xxxxxxxxxx.atlassian.net/secure/projectavatar?size=medium&s=medium&pid=10000&avatarId=10412"
}
},
"customfield_10032": {
"id": "2",
"name": "Time to first response",
"_links": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/servicedeskapi/request/10210/sla/2"
},
"completedCycles": [],
"ongoingCycle": {
"startTime": {
"iso8601": "2021-01-25T20:12:11+0000",
"jira": "2021-01-25T20:12:11.592+0000",
"friendly": "Yesterday 08:12",
"epochMillis": 1611605531592
},
"breachTime": {
"iso8601": "2021-01-26T12:30:00+0000",
"jira": "2021-01-26T12:30:00.000+0000",
"friendly": "Today 12:30",
"epochMillis": 1611664200000
},
"breached": false,
"paused": false,
"withinCalendarHours": false,
"goalDuration": {
"millis": 14400000,
"friendly": "4h"
},
"elapsedTime": {
"millis": 0,
"friendly": "0m"
},
"remainingTime": {
"millis": 14400000,
"friendly": "4h"
}
}
},
"fixVersions": [],
"customfield_10034": {
"languageCode": "en",
"displayName": "English"
},
"resolution": null,
"customfield_10037": null,
"customfield_10027": null,
"customfield_10028": null,
"customfield_10029": null,
"resolutiondate": null,
"workratio": -1,
"lastViewed": "2021-01-25T20:12:11.936+0000",
"watches": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/issue/ITSD-202/watchers",
"watchCount": 1,
"isWatching": true
},
"created": "2021-01-25T20:12:11.592+0000",
"customfield_10020": null,
"customfield_10021": null,
"customfield_10022": null,
"customfield_10023": null,
"priority": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/priority/3",
"iconUrl": "https://xxxxxxxxxx.atlassian.net/images/icons/priorities/medium.svg",
"name": "Medium",
"id": "3"
},
"customfield_10024": null,
"customfield_10025": null,
"labels": [],
"customfield_10026": [],
"customfield_10016": null,
"customfield_10017": null,
"customfield_10018": {
"hasEpicLinkFieldDependency": false,
"showField": false,
"nonEditableReason": {
"reason": "PLUGIN_LICENSE_ERROR",
"message": "The Parent Link is only available to Jira Premium users."
}
},
"customfield_10019": "0|i0013b:",
"timeestimate": null,
"versions": [],
"assignee": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/user?accountId=12345678912345678912345",
"accountId": "12345678912345678912345",
"emailAddress": "first.last#xxxxxxxxxx.co.uk",
"avatarUrls": {
"48x48": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png",
"24x24": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png",
"16x16": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png",
"32x32": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png"
},
"displayName": "First Last",
"active": true,
"timeZone": "Europe/London",
"accountType": "atlassian"
},
"updated": "2021-01-25T20:12:14.321+0000",
"status": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/status/10001",
"description": "This was auto-generated by Jira Service Desk during workflow import",
"iconUrl": "https://xxxxxxxxxx.atlassian.net/images/icons/status_generic.gif",
"name": "Waiting for support",
"id": "10001",
"statusCategory": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/statuscategory/4",
"id": 4,
"key": "indeterminate",
"colorName": "yellow",
"name": "In Progress"
}
},
"components": [],
"customfield_10050": null,
"customfield_10051": null,
"timeoriginalestimate": null,
"customfield_10052": null,
"customfield_10053": null,
"description": null,
"customfield_10010": null,
"customfield_10014": null,
"customfield_10015": null,
"customfield_10005": null,
"customfield_10049": null,
"customfield_10006": null,
"customfield_10007": null,
"security": null,
"customfield_10008": null,
"customfield_10009": null,
"summary": "Barry Test",
"creator": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/user?accountId=12345678912345678912345",
"accountId": "12345678912345678912345",
"emailAddress": "first.last#xxxxxxxxxx.co.uk",
"avatarUrls": {
"48x48": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png",
"24x24": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png",
"16x16": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png",
"32x32": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png"
},
"displayName": "First Last",
"active": true,
"timeZone": "Europe/London",
"accountType": "atlassian"
},
"customfield_10040": null,
"customfield_10041": null,
"customfield_10042": null,
"customfield_10043": null,
"reporter": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/api/3/user?accountId=12345678912345678912345",
"accountId": "12345678912345678912345",
"emailAddress": "first.last#xxxxxxxxxx.co.uk",
"avatarUrls": {
"48x48": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png",
"24x24": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png",
"16x16": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png",
"32x32": "https://secure.gravatar.com/avatar/2758e009bbe7f2348bfdf52d653b6a2b?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FBE-1.png"
},
"displayName": "First Last",
"active": true,
"timeZone": "Europe/London",
"accountType": "atlassian"
},
"customfield_10044": null,
"customfield_10000": "{}",
"customfield_10001": null,
"customfield_10045": null,
"customfield_10046": null,
"customfield_10002": [
{
"id": "4",
"name": "xxxxxxxxxx.co.uk",
"_links": {
"self": "https://xxxxxxxxxx.atlassian.net/rest/servicedeskapi/organization/4"
}
}
],
"customfield_10003": null,
"customfield_10047": null,
"customfield_10048": null,
"customfield_10004": null,
"customfield_10038": null,
"customfield_10039": null,
"environment": null,
"duedate": null,
"progress": {
"progress": 0,
"total": 0
}
}
}
]
}
And this is how I am deseriazling it and trying to return the values.
var root = JsonConvert.DeserializeObject<Rootobject2>(response.Content);
foreach (var issue in root.issues)
{
string id = issue.id.ToString();
string key = issue.key.ToString();
string summary = issue.fields.summary.ToString();
string creatoremail = issue.fields.creator.emailAddress.ToString();
public class Rootobject2
{
public string expand { get; set; }
public int startAt { get; set; }
public int maxResults { get; set; }
public int total { get; set; }
public Issue[] issues { get; set; }
}
public class Issue
{
public string expand { get; set; }
public string id { get; set; }
public string self { get; set; }
public string key { get; set; }
public Fields fields { get; set; }
}
public class Fields
{
public DateTime statuscategorychangedate { get; set; }
public Issuetype issuetype { get; set; }
public int? timespent { get; set; }
public object customfield_10030 { get; set; }
public Customfield_10031 customfield_10031 { get; set; }
public Project project { get; set; }
public Customfield_10032 customfield_10032 { get; set; }
public object[] fixVersions { get; set; }
public Customfield_10034 customfield_10034 { get; set; }
public Resolution resolution { get; set; }
public object customfield_10037 { get; set; }
public object customfield_10027 { get; set; }
public object customfield_10028 { get; set; }
public object customfield_10029 { get; set; }
public DateTime? resolutiondate { get; set; }
public int workratio { get; set; }
public DateTime? lastViewed { get; set; }
public Watches watches { get; set; }
public DateTime created { get; set; }
public object customfield_10020 { get; set; }
public object customfield_10021 { get; set; }
public object customfield_10022 { get; set; }
public Priority priority { get; set; }
public object customfield_10023 { get; set; }
public DateTime? customfield_10024 { get; set; }
public string customfield_10025 { get; set; }
public object[] customfield_10026 { get; set; }
public object[] labels { get; set; }
public object customfield_10016 { get; set; }
public object customfield_10017 { get; set; }
public Customfield_10018 customfield_10018 { get; set; }
public string customfield_10019 { get; set; }
public int? timeestimate { get; set; }
public object[] versions { get; set; }
public Assignee assignee { get; set; }
public DateTime updated { get; set; }
public Status status { get; set; }
public Component[] components { get; set; }
public object customfield_10050 { get; set; }
public object customfield_10051 { get; set; }
public object timeoriginalestimate { get; set; }
public object customfield_10052 { get; set; }
public object customfield_10053 { get; set; }
public Description description { get; set; }
public Customfield_10010 customfield_10010 { get; set; }
public object customfield_10014 { get; set; }
public object customfield_10015 { get; set; }
public object customfield_10005 { get; set; }
public object customfield_10049 { get; set; }
public object customfield_10006 { get; set; }
public object customfield_10007 { get; set; }
public object security { get; set; }
public object customfield_10008 { get; set; }
public object customfield_10009 { get; set; }
public string summary { get; set; }
public Creator creator { get; set; }
public object customfield_10040 { get; set; }
public object customfield_10041 { get; set; }
public object customfield_10042 { get; set; }
public object customfield_10043 { get; set; }
public Reporter reporter { get; set; }
public string customfield_10000 { get; set; }
public object customfield_10044 { get; set; }
public object customfield_10045 { get; set; }
public object customfield_10001 { get; set; }
public object customfield_10046 { get; set; }
public Customfield_10002[] customfield_10002 { get; set; }
public object customfield_10047 { get; set; }
public object customfield_10003 { get; set; }
public object customfield_10048 { get; set; }
public object customfield_10004 { get; set; }
public object customfield_10038 { get; set; }
public object customfield_10039 { get; set; }
public object environment { get; set; }
public object duedate { get; set; }
public Progress progress { get; set; }
}
(Dictionary created by doing paste special values in Visual Studio)
The issue I am seeing, I get "Object reference not set to an instance of an object." on
foreach (var issue in root.issues)
Any help greatly appreciated
Your class for deserialization should look something like this
public class Issuetype {
public string self { get; set; }
public string id { get; set; }
public string description { get; set; }
public string iconUrl { get; set; }
public string name { get; set; }
public bool subtask { get; set; }
public int avatarId { get; set; }
}
public class Links {
public string self { get; set; }
}
public class StartTime {
public DateTime iso8601 { get; set; }
public DateTime jira { get; set; }
public string friendly { get; set; }
public long epochMillis { get; set; }
}
public class BreachTime {
public DateTime iso8601 { get; set; }
public DateTime jira { get; set; }
public string friendly { get; set; }
public long epochMillis { get; set; }
}
public class GoalDuration {
public int millis { get; set; }
public string friendly { get; set; }
}
public class ElapsedTime {
public int millis { get; set; }
public string friendly { get; set; }
}
public class RemainingTime {
public int millis { get; set; }
public string friendly { get; set; }
}
public class OngoingCycle {
public StartTime startTime { get; set; }
public BreachTime breachTime { get; set; }
public bool breached { get; set; }
public bool paused { get; set; }
public bool withinCalendarHours { get; set; }
public GoalDuration goalDuration { get; set; }
public ElapsedTime elapsedTime { get; set; }
public RemainingTime remainingTime { get; set; }
}
public class Customfield10031 {
public string id { get; set; }
public string name { get; set; }
public Links _links { get; set; }
public List<object> completedCycles { get; set; }
public OngoingCycle ongoingCycle { get; set; }
}
public class AvatarUrls {
public string _48x48 { get; set; }
public string _24x24 { get; set; }
public string _16x16 { get; set; }
public string _32x32 { get; set; }
}
public class Project {
public string self { get; set; }
public string id { get; set; }
public string key { get; set; }
public string name { get; set; }
public string projectTypeKey { get; set; }
public bool simplified { get; set; }
public AvatarUrls avatarUrls { get; set; }
}
public class Customfield10032 {
public string id { get; set; }
public string name { get; set; }
public Links _links { get; set; }
public List<object> completedCycles { get; set; }
public OngoingCycle ongoingCycle { get; set; }
}
public class Customfield10034 {
public string languageCode { get; set; }
public string displayName { get; set; }
}
public class Watches {
public string self { get; set; }
public int watchCount { get; set; }
public bool isWatching { get; set; }
}
public class Priority {
public string self { get; set; }
public string iconUrl { get; set; }
public string name { get; set; }
public string id { get; set; }
}
public class NonEditableReason {
public string reason { get; set; }
public string message { get; set; }
}
public class Customfield10018 {
public bool hasEpicLinkFieldDependency { get; set; }
public bool showField { get; set; }
public NonEditableReason nonEditableReason { get; set; }
}
public class Assignee {
public string self { get; set; }
public string accountId { get; set; }
public string emailAddress { get; set; }
public AvatarUrls avatarUrls { get; set; }
public string displayName { get; set; }
public bool active { get; set; }
public string timeZone { get; set; }
public string accountType { get; set; }
}
public class StatusCategory {
public string self { get; set; }
public int id { get; set; }
public string key { get; set; }
public string colorName { get; set; }
public string name { get; set; }
}
public class Status {
public string self { get; set; }
public string description { get; set; }
public string iconUrl { get; set; }
public string name { get; set; }
public string id { get; set; }
public StatusCategory statusCategory { get; set; }
}
public class Creator {
public string self { get; set; }
public string accountId { get; set; }
public string emailAddress { get; set; }
public AvatarUrls avatarUrls { get; set; }
public string displayName { get; set; }
public bool active { get; set; }
public string timeZone { get; set; }
public string accountType { get; set; }
}
public class Reporter {
public string self { get; set; }
public string accountId { get; set; }
public string emailAddress { get; set; }
public AvatarUrls avatarUrls { get; set; }
public string displayName { get; set; }
public bool active { get; set; }
public string timeZone { get; set; }
public string accountType { get; set; }
}
public class Customfield10002 {
public string id { get; set; }
public string name { get; set; }
public Links _links { get; set; }
}
public class Progress {
public int progress { get; set; }
public int total { get; set; }
}
public class Fields {
public DateTime statuscategorychangedate { get; set; }
public Issuetype issuetype { get; set; }
public object timespent { get; set; }
public object customfield_10030 { get; set; }
public Customfield10031 customfield_10031 { get; set; }
public Project project { get; set; }
public Customfield10032 customfield_10032 { get; set; }
public List<object> fixVersions { get; set; }
public Customfield10034 customfield_10034 { get; set; }
public object resolution { get; set; }
public object customfield_10037 { get; set; }
public object customfield_10027 { get; set; }
public object customfield_10028 { get; set; }
public object customfield_10029 { get; set; }
public object resolutiondate { get; set; }
public int workratio { get; set; }
public DateTime lastViewed { get; set; }
public Watches watches { get; set; }
public DateTime created { get; set; }
public object customfield_10020 { get; set; }
public object customfield_10021 { get; set; }
public object customfield_10022 { get; set; }
public object customfield_10023 { get; set; }
public Priority priority { get; set; }
public object customfield_10024 { get; set; }
public object customfield_10025 { get; set; }
public List<object> labels { get; set; }
public List<object> customfield_10026 { get; set; }
public object customfield_10016 { get; set; }
public object customfield_10017 { get; set; }
public Customfield10018 customfield_10018 { get; set; }
public string customfield_10019 { get; set; }
public object timeestimate { get; set; }
public List<object> versions { get; set; }
public Assignee assignee { get; set; }
public DateTime updated { get; set; }
public Status status { get; set; }
public List<object> components { get; set; }
public object customfield_10050 { get; set; }
public object customfield_10051 { get; set; }
public object timeoriginalestimate { get; set; }
public object customfield_10052 { get; set; }
public object customfield_10053 { get; set; }
public object description { get; set; }
public object customfield_10010 { get; set; }
public object customfield_10014 { get; set; }
public object customfield_10015 { get; set; }
public object customfield_10005 { get; set; }
public object customfield_10049 { get; set; }
public object customfield_10006 { get; set; }
public object customfield_10007 { get; set; }
public object security { get; set; }
public object customfield_10008 { get; set; }
public object customfield_10009 { get; set; }
public string summary { get; set; }
public Creator creator { get; set; }
public object customfield_10040 { get; set; }
public object customfield_10041 { get; set; }
public object customfield_10042 { get; set; }
public object customfield_10043 { get; set; }
public Reporter reporter { get; set; }
public object customfield_10044 { get; set; }
public string customfield_10000 { get; set; }
public object customfield_10001 { get; set; }
public object customfield_10045 { get; set; }
public object customfield_10046 { get; set; }
public List<Customfield10002> customfield_10002 { get; set; }
public object customfield_10003 { get; set; }
public object customfield_10047 { get; set; }
public object customfield_10048 { get; set; }
public object customfield_10004 { get; set; }
public object customfield_10038 { get; set; }
public object customfield_10039 { get; set; }
public object environment { get; set; }
public object duedate { get; set; }
public Progress progress { get; set; }
}
public class Issue {
public string expand { get; set; }
public string id { get; set; }
public string self { get; set; }
public string key { get; set; }
public Fields fields { get; set; }
}
public class Root {
public string expand { get; set; }
public int startAt { get; set; }
public int maxResults { get; set; }
public int total { get; set; }
public List<Issue> issues { get; set; }
}
and you'd deserialize like this
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
Always try to see references when creting json objects, I use this page
As commmented below, this would be the main:
using Newtonsoft.Json;
using System;
using System.IO;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Root myDeserializedClass = JsonConvert.DeserializeObject<Root> (File.ReadAllText(#"response.json"));
foreach (var issue in myDeserializedClass.issues)
{
string id = issue.id.ToString();
string key = issue.key.ToString();
string summary = issue.fields.summary.ToString();
string creatoremail = issue.fields.creator.emailAddress.ToString();
}
}
}
}
I think the problem you're having might be the way you're writting your foreach? I mean the code seems to be lacking something, but perhaps you shortened it.

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 with mixture of dynamic and static keys

I have a JSON object with a dynamic key for the properties I wish to map to a class. I'm uncertain how to build my class to deserialize with JSON.NET. I need the values from the 'results' and 'more' keys at the upper level and also the the values from the 'timesheets' key.
Here is my JSON data.
{
"results": {
"timesheets": {
"7994790": {
"id": 7994790,
"user_id": 165502,
"jobcode_id": 11267673,
"start": "2019-12-20T05:48:00-05:00",
"end": "2019-12-20T13:44:00-05:00",
"duration": 28560,
"date": "2019-12-20",
"tz": -5,
"tz_str": "tsET",
"type": "regular",
"location": "Android App",
"on_the_clock": false,
"locked": 0,
"notes": "",
"customfields": {
"20251": "",
"19647": "Laborer",
"20327": "",
"19648": ""
},
"last_modified": "2019-12-20T20:28:48+00:00",
"attached_files": [],
"created_by_user_id": 165502
},
"8087496": {
"id": 8087496,
"user_id": 165502,
"jobcode_id": 2415904,
"start": "2019-12-20T13:44:00-05:00",
"end": "2019-12-20T15:11:00-05:00",
"duration": 5220,
"date": "2019-12-20",
"tz": -5,
"tz_str": "tsET",
"type": "regular",
"location": "Android App",
"on_the_clock": false,
"locked": 0,
"notes": "",
"customfields": {
"20251": "",
"19647": "Laborer",
"20327": "",
"19648": ""
},
"last_modified": "2019-12-20T20:28:49+00:00",
"attached_files": [],
"created_by_user_id": 165502
}
}
},
"more": false
}
And my classes as I currently have them which returns this error.
System.ArgumentNullException: 'Value cannot be null.
Parameter name: values'
public class RootObject
{
public Results results { get; set; }
public bool more { get; set; }
}
public class Results
{
public Timesheets timesheets { get; set; }
}
public class Timesheets
{
public Dictionary<int, TimesheetDetails> timesheetsdetails { get; set; }
}
public class TimesheetDetails
{
public int id { get; set; }
public int user_id { get; set; }
public int jobcode_id { get; set; }
public DateTime start { get; set; }
public DateTime end { get; set; }
public int duration { get; set; }
public string date { get; set; }
public int tz { get; set; }
public string tz_str { get; set; }
public string type { get; set; }
public string location { get; set; }
public bool on_the_clock { get; set; }
public int locked { get; set; }
public string notes { get; set; }
public DateTime last_modified { get; set; }
public List<object> attached_files { get; set; }
public int created_by_user_id { get; set; }
}
var stuff = JsonConvert.DeserializeObject<RootObject>(result.Content);
Console.WriteLine(string.Join(",", stuff.results.timesheets.timesheetsdetails));
First of all your json is not valid. After the end of the first timesheet data, there should be a , You can use any json validator online simply to validate it.
And in your model the Results is not valid according to the json. The below one works for me.
public class Response
{
[JsonProperty("results")] public TimeSheetResponse TimeSheetResponse { get; set; }
[JsonProperty("more")] public bool More { get; set; }
}
public class TimeSheetResponse
{
[JsonProperty("timesheets")] public Dictionary<string, Timesheet> Timesheets { get; set; }
}
public class Timesheet
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("user_id")]
public long UserId { get; set; }
[JsonProperty("jobcode_id")]
public long JobcodeId { get; set; }
[JsonProperty("start")] public DateTimeOffset Start { get; set; }
[JsonProperty("end")] public DateTimeOffset End { get; set; }
[JsonProperty("duration")] public long Duration { get; set; }
[JsonProperty("date")] public DateTimeOffset Date { get; set; }
[JsonProperty("tz")] public long Tz { get; set; }
[JsonProperty("tz_str")] public string TzStr { get; set; }
[JsonProperty("type")] public string Type { get; set; }
[JsonProperty("location")] public string Location { get; set; }
[JsonProperty("on_the_clock")] public bool OnTheClock { get; set; }
[JsonProperty("locked")] public long Locked { get; set; }
[JsonProperty("notes")] public string Notes { get; set; }
[JsonProperty("customfields")] public Dictionary<string, string> Customfields { get; set; }
[JsonProperty("last_modified")] public DateTimeOffset LastModified { get; set; }
[JsonProperty("attached_files")] public List<object> AttachedFiles { get; set; }
[JsonProperty("created_by_user_id")]
public long CreatedByUserId { get; set; }
}
To deserialize to Object..
var timeSheetResult = JsonConvert.DeserializeObject<Response>(data);

Categories