c# json deserialization complex objects - c#

I have a problem deserializing a json file, this is the json:
[
{
"id": "id",
"number": "48",
"date": "17-01-2020",
"details": [
{
"id": "id",
"code": "code",
"description": "desc"
},
{
"id": "id",
"code": "code",
"description": "desc"
}
],
"address": "add",
"note": null
},
{
"id": "id",
"number": "55",
"date": "17-01-2020",
"details": [
{
"id": "id",
"code": "code",
"description": "desc"
},
{
"id": "id",
"code": "code",
"description": "desc"
}
],
"address": "add",
"note": null
}
]
this is my code:
var result = httpClient.GetAsync(".....").Result;
List<Docu> doc= new JavaScriptSerializer().Deserialize<List<Docu>>(result.Content.ReadAsStringAsync().Result);
class Docu contains definition of id, number, date, details and:
public List<Details> det{ get; set; }
Class Details contains id, code and description definition
I can deserialize everything except complex object details, it returns null from deserialization, how I can fix this? I need to fill the list of details

You have wrong name for List<Details> property
it should be
public List<Details> details{ get; set; }
according to json you have shown

Related

Need to get array of values from JSON data

I have the following JSON that is returned to me from an API call. I’m trying to just get the information from a property called “products”. Once I have that into an array or list I need to look for a specific product name and then one of it’s properties.
I’ve tried a handful of different things without any luck. I’m also searching and not finding what I’m looking for in my scenario.
If I use the following, I can get the data into parseJson object but from there I don’t understand how I can pull just the “products” into an array so I can loop through them looking for a specific product and it’s value.
dynamic parseJson = JsonConvert.DeserializeObject(response.Content);
I also tried this but had no luck either.
dynamic parseJson = JsonConvert.DeserializeObject<AccurateApiResult>(response.Content);
public class AccurateApiResult
{
public List<AccurateProduct> products { get; set; }
}
public class AccurateProduct
{
public int id { get; set; }
public string productType { get; set; }
public string status { get; set; }
public string result { get; set; }
public bool flag { get; set; }
}
Here is the sample data and I’m only interested in the “products” section. How can I pull just that data?
[
{
"resource": "ORDER",
"id": "Y10046727",
"created": "2022-06-28T13:18:17Z",
"updated": "2022-06-28T13:18:17Z",
"workflow": "INTERACTIVE",
"candidate": {
"firstName": "Marcus",
"lastName": "Willis",
"middleName": null,
"suffix": null,
"dateOfBirth": "1990-01-01",
"ssn": "111111111",
"email": null,
"phone": "240-5798551",
"address": "3433 Lumar dr",
"city": "Fort Washington",
"region": "MD",
"country": "US",
"postalCode": "20744",
"governmentId": {
"country": "US",
"type": null,
"number": null
},
"aliases": [],
"educations": [
{
"school": "Test University",
"country": "US",
"region": "CA",
"city": "Irvine",
"degree": null,
"major": null,
"startDate": null,
"endDate": null,
"graduated": false,
"graduationDate": null,
"presentlyEnrolled": false
}
],
"prevEmployed": null,
"employments": [],
"convicted": null,
"convictions": null,
"references": [],
"addressHistory": []
},
"completed": "2022-07-07T01:59:13Z",
"supportReferenceId": "Y10046727",
"status": "COMPLETE",
"result": "Meets Requirements",
"products": [
{
"id": 66134505,
"productType": "AELS",
"status": "COMPLETE",
"result": "NOT APPLICABLE",
"flag": false
},
{
"id": 66134506,
"productType": "ADJ",
"status": "COMPLETE",
"result": "NOT APPLICABLE",
"flag": false
},
{
"id": 66134508,
"productType": "MOV",
"status": "COMPLETE",
"result": "Invalid SSN",
"flag": false
},
{
"id": 66144583,
"productType": "MVR",
"status": "COMPLETE",
"result": "NOT APPLICABLE",
"flag": false
},
{
"id": 66144584,
"productType": "F/M",
"status": "COMPLETE",
"result": "NO RECORD FOUND",
"flag": false
},
{
"id": 66144587,
"productType": "EDU",
"status": "COMPLETE",
"result": "NOT APPLICABLE",
"flag": false
},
{
"id": 66144588,
"productType": "DL5D",
"status": "COMPLETE",
"result": "Negative",
"flag": false
}
],
"percentageComplete": 0,
"candidateInfoChanged": false,
"searchId": 66134503,
"subjectId": 10121219,
"requestor": "maegan#email.com"
}
you can try this code
var parsedJsonProducts = (JArray) JArray.Parse(response.Content)[0]["products"];
List<AccurateProduct> products = parsedJsonProducts.ToObject<List<AccurateProduct>>();

NEST Elastic Search - query a term with spaces

I'm having hard time implementing autocomplete in elastic for DisplayName property for the text that have spaces in it, here is the setup of the field:
"DisplayName": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256,
"normalizer": "caseinsensitive"
},
"prefix": {
"type": "text",
"analyzer": "startswith"
}
}
},
"id": {
"type": "keyword"
}
Here is the startwith analyzer definition:
"analysis": {
"analyzer": {
"startswith": {
"char_filter": [
"html_strip"
],
"filter": [
"lowercase"
],
"tokenizer": "keyword",
"type": "custom"
}
},
"normalizer": {
"caseinsensitive": {
"filter": [
"lowercase",
"asciifolding"
],
"type": "custom"
}
}
},
"creation_date": "1565034410554",
"mapping": {
"total_fields": {
"limit": "5000"
}
},
"number_of_shards": "5",
"provided_name": "streetsmart"
In my query builder here is the query that tries to grab the result:
_type:User AND (DisplayName.prefix:Joseph adam* OR UserPrincipalName.prefix:Joseph adam*)"
and the result that I get is all the names that contains Adam which the result should be Joseph Adam Jr,
Does anyone know what I should do?
I am not aware of c# and .net syntax, but adding a working example with index data, search query, and search result in JSON format.
You can also use Match phrase prefix query that :
Returns documents that contain the words of a provided text, in the
same order as provided. The last term of the provided text is treated
as a prefix, matching any words that begin with that term.
Index Data:
{
"name": "Adam"
}
{
"name": "Joseph Adam Sr"
}
{
"name": "Joseph Adam Jr"
}
Search Query:
{
"query": {
"multi_match": {
"query": "Joseph Adam",
"fields": [
"name"
],
"type": "phrase_prefix"
}
}
}
Search Result:
"hits": [
{
"_index": "stof_64163994",
"_type": "_doc",
"_id": "1",
"_score": 0.54037446,
"_source": {
"name": "Joseph Adam Jr"
}
},
{
"_index": "stof_64163994",
"_type": "_doc",
"_id": "3",
"_score": 0.54037446,
"_source": {
"name": "Joseph Adam Sr"
}
}
]

how to valilidate a condtion for list in JSON object in C#

I have a JSON file, where i have to perform a data validation based on a json element.
below is my json file
[
{
"id": "5241585099662481339",
"displayName": "Music",
"name": "music",
"slug": "music",
"imageUrl": "http://mno.com"
},
{
"id": "6953585193220490118",
"displayName": "Celebrities",
"name": "celebrities",
"slug": "celebrities",
"imageUrl": "http://ijk.com"
},
{
"id": "5757029936226020304",
"displayName": "Entertainment",
"name": "entertainment",
"slug": "entertainment",
"imageUrl": "http://pqr.com"
},
{
"id": "3718",
"displayName": "Saturday Night Live",
"name": "saturday night live",
"slug": "saturday-night-live",
"imageUrl": "http://efg.com"
},
{
"id": "8113008320053776960",
"displayName": "Hollywood",
"name": "hollywood",
"slug": "hollywood",
"imageUrl": "http://qwe.com"
}
]
Below is code snippet
var list = JsonConvert.DeserializeObject<List<MyItem>>(json);
if (list.Any(e => e.id =="3718"))
{
//How do get the exact displayName on the if condtion
}
public class MyItem
{
public string id;
public string displayName;
public string name;
public string slug;
public string imageUrl;
}
Here i want the displayname value based on the if condtion passed. So inside my if loop if put list.displayname i need the value to printed as Saturday Night Live
// name will be null if there isn't any item where id == 3718
var name = list.FirstOrDefault(item => string.Equals(item.id, "3718"))?.displayName;
// InvalidOperationException will be thrown if there isn't any item where id == 3718
var name = list.First(item => string.Equals(item.id, "3718")).displayName;
Check this:
var name = list.Where(e=>e.id=="3718").Select(x=>x.displayName);

Finding distinct and removing duplicates from object [duplicate]

This question already has answers here:
Remove duplicates in the list using linq
(11 answers)
Closed 2 years ago.
I am very new to LINQ. I have run to a scenario where I need to find distinct from an object and remove the others. Please help.
I have tried like this
var xyz = referal.GroupBy(i => i.Select(x => x.identifier).Distinct().Select(g=>g));
but it is not returning the distinct values. Thanks in advance.
Sample Object :
{
"referral_type": [
{
"type": "MOBILE",
"invitee": [
{
"identifier": "12345678",
"name": "Test2",
"invited_on": "2020-01-29 12:25:46.0",
"till": {
"code": "",
"name": ""
}
},
{
"identifier": "98765432",
"name": "Test1",
"invited_on": "2020-01-29 13:37:36.0",
"till": {
"code": "",
"name": ""
}
},
{
"identifier": "12345678",
"name": "Harry Test",
"invited_on": "2020-01-29 13:55:32.0",
"till": {
"code": "",
"name": ""
}
},
{
"identifier": "98765432",
"name": "Harry Test",
"invited_on": "2020-01-29 13:55:32.0",
"till": {
"code": "",
"name": ""
}
}
]
}
]
}
So I want to check the distinct identifier and take the first one irresoective of other values, something like this
{
"referral_type": [
{
"type": "MOBILE",
"invitee": [
{
"identifier": "12345678",
"name": "Test2",
"invited_on": "2020-01-29 12:25:46.0",
"till": {
"code": "",
"name": ""
}
},
{
"identifier": "98765432",
"name": "Test1",
"invited_on": "2020-01-29 13:37:36.0",
"till": {
"code": "",
"name": ""
}
}
]
}
]
}
You need to implement the interface IEquatable<T> class "invitee", because Dinstinct use this to compare object. On this way i think you are comparing memory references.

How do I arrange similar data from multiple json files but in different format?

I am new to JSON and trying to develop a comparison table with data coming from 2 different JSON files as follows.
Json File 1
"data":[
{
"EffectiveDate": "2017-04-01T00:00:00Z",
"IncludedQuantity": 0,
"Category": "VM",
"Id": "d0bf9053",
"Name": "Element1",
"Rates": {
"0": 0.04
},
"Region": "US",
"Status": "Active",
"SubCategory": "S1",
"Tags": [],
"Unit": "Hours"
},
{
"EffectiveDate": "2017-02-01T00:00:00Z",
"IncludedQuantity": 0,
"Category": "DS",
"Id": "8b7672d4",
"Name": "Element2",
"Rates": {
"0": 4.0177
},
"Region": "UK",
"Status": "Active",
"SubCategory": "S2",
"Tags": [],
"Unit": "Days"
}]
Json File 2
"data":{
"d0bf9053":{
"EffectiveDate": "2017-04-01T00:00:00Z",
"IncludedQuantity": 0,
"Category": "VM",
"Id": "d0bf9053",
"Attributes":{
"Name": "Element1",
"Rates": {
"0": 5
},
"Region": "US",
"Status": "Active",
"SubCategory": "S1",
"Tags": [],
"Unit": "Hours"
}
},
"8b7672d4":{
"EffectiveDate": "2017-02-01T00:00:00Z",
"IncludedQuantity": 0,
"Category": "DS",
"Id": "8b7672d4",
"Attributes":{
"Name": "Element2",
"Rates": {
"0": 1
},
"Region": "UK",
"Status": "Active",
"SubCategory": "S2",
"Tags": [],
"Unit": "Days"
}
}}
Now I have to read this data and merge it to create a comparison based on rates and categories. I have created a Dot.Net Console Application and trying to use SQL Server to store the information. Now I am able to read JSON File 1 easily. But I am facing difficulty in storing values from JSON File 2. How do I solve this or am I wrong somewhere.
Thanks in advance.
The problem here is that you have dynamic property names in the second JSON file (Json File 2) and you are probably having trouble deserializing that JSON into a .Net Class, right?
Here are some examples that you can use to deserialize both Json1 and Json2 Types:
public class dataJson1
{
public List<Detail> data { get; set; }
}
public class dataJson2
{
public Dictionary<string, Detail> data { get; set; }
}
public class Detail
{
public DateTime EffectiveDate { get; set; }
public int IncludedQuantity { get; set; }
public string Category { get; set; }
//add the rest of the props here
}
That should get you started, once it's deserialized into those Objects, comparing them should be trivial.

Categories

Resources