Environment : -angular for the web app -c# for my api -sql server for the data base
I have this informations from my data base :
public class Traductions
{
public int Id { get; set; }
public int Lot { get; set; }
public string Code { get; set; }
public string Description { get; set; }
public string IdLangage { get; set; }
public string LibelleLangage { get; set; }
public string Traduction { get; set; }
}
If i make a get with the api that return me that format Json informations :
[
{
"Id": 1,
"Lot" : 3,
"Code" : "ABANDONDUTRAITEMENT",
"Description" : "",
"IdLangage": "FR",
"LibelleLangage": "Francais",
"Traduction": "Abandon du traitement"
},
{
"Id": 2,
"Lot" : 3,
"Code" : "ABANDONDUTRAITEMENT",
"Description" : "",
"IdLangage": "EN",
"LibelleLangage": "English",
"Traduction": "Abandonment of processing"
}
]
But i want this type of Json format :
[
{
"Code": "ABANDONDUTRAITEMENT",
"FR": "Abandon du traitement",
"EN": "Abandonment of processing"
},
]
I want to group the informations by Code to return all the Translations (traduction) by Code.
I think i have to do it in my api and not in my angular application
How can i do it ? With linq group by?
somthing like this?
traductions.GroupBy(p => p.Code,
(k, c) => new
{
Code = k,
Data = c
}
).ToList();
https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.groupby?view=net-6.0
you can change the select to be how you want to represent the data in your angular application.
Related
I have two JSONs files Country & Ceremony
Country JSON:
[
{
"Short": "AF",
"Name": "Afghanistan"
},
{
"Short": "AN",
"Name": "Netherlands Antilles"
},
{
"Short": "AI",
"Name": "Anguilla"
},
{
"Short": "AL",
"Name": "Albania"
} ]
Ceremony JSON:
[
{
"CName": "Fitr",
"CStart": "2021-11-10T09:00:00",
"CEnd": "2021-11-14T09:00:00",
"Loc": {
"Info": "",
"Short": "AF"
}
},
{
"CName": "Azha",
"CStart": "2023-06-17T09:18:44",
"CEnd": "2023-06-18T09:18:44",
"Loc": {
"Info": "",
"Short": "AI"
}
},
{
"CName": "Azha",
"CStart": "2022-01-05T00:00:00",
"CEnd": "2022-01-05T23:59:59",
"Loc": {
"Info": "",
"Short": "AL"
}
},
{
"CName": "Fitr",
"CStart": "2022-01-05T00:00:00",
"CEnd": "2022-01-05T23:59:59",
"Loc": {
"Info": "",
"Short": "AN",
}
}
]
Country Model Class
public class Country
{
public string Short{ get; set; }
public string Name { get; set; }
}
Ceremony Model Class
public class Ceremony
{
public string CName { get; set; }
public DateTime CStart { get; set; }
public DateTime End { get; set; }
public Loc loc { get; set; }
}
Loc Model Class
public class Loc
{
public string Info { get; set; }
public string Short { get; set; }
}
I want to show Country (Name) with a connection to Ceremony, Loc, and Short, so that when I read the Ceremony data in front of Short, I can see the full name of the country. Country full name should come from Country JSON.
Results should be like this:
CName CStart CEnd Short Name
Fitr "" "" AF Afghanistan
Azha "" "" AI Anguilla
How can I use LINQ to display the top countries i.e., using (Short) with the most ceremonies in 2021?
You can join two entities on ShortName like below :
var countries = ...;
var ceremonies = ...;
var result = (from c in countries
join ce in ceremonies on c.Short equals ce.loc.Short
select new {
ce.CName,
ce.CStart,
ce.Cend,
c.Short,
c.Name
}).Where(r=> r.CStart.Year == 2021).
GroupBy(r=> r.Short).Select(r=> new { Short = r.Key,
EventCount = r.Count()}).OrderByDescending(r=> r.EventCount)
.ToArray();
Edit
Added grouping and sorting as the question evolves.
I'm stuck in using NetTopologySuite with geojson file.
I want to get all the points from the geojson and then use the IsWithinDistance() method to get all the points within certain distance. I could deserialize the data and get the coordinates but the method doesn't work. I suppose that the method needs the points to be converted to WKB ? please correct me if I'm mistaken.
I could successfully execute the method when my first source of data stored in database but from json it doesn't work.
This is my controller :
public IActionResult GetWeather()
{
IList<WeatherViewModel> Tags = new List<WeatherViewModel>();
var geometryFactory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326);
var searchAreaCoordinate = new NetTopologySuite.Geometries.Coordinate(-1.882, 52.486);
var searchArea = geometryFactory.CreatePoint(searchAreaCoordinate);
Root weather = JsonConvert.DeserializeObject<Root>(System.IO.File.ReadAllText(#"C:\local\weatherx.json"));
var features = (from c in weather.features select c)
.Select(x=> new {x.id,x.type,x.geometry.coordinates})
// .Where(x=>x.Coor.IsWithinDistance(searchArea, 300))
.ToList();
;
foreach (var item in features)
{
Tags.Add(new WeatherViewModel()
{
id = item.id,
type = item.type,
Long = item.coordinates[0],
Lat = item.coordinates[1],
WKT = new NetTopologySuite.Geometries.Coordinate( item.coordinates[0] , item.coordinates[1])
}
);
}
return View(Tags);
}
Part of my json class:
public class Root
{
public string type { get; set; }
public ParameterDescription parameter_description { get; set; }
public List<double> bbox { get; set; }
public List<Feature> features { get; set; }
}
public class Geometry
{
public string type { get; set; }
public List<double> coordinates { get; set; }
}
public class Feature
{
public string id { get; set; }
public string type { get; set; }
public Properties properties { get; set; }
public Geometry geometry { get; set; }
public Geometry Coor {get;set;}
}
Here is part of my geojson:
{
"type": "FeatureCollection",
"features": [
{
"id": "1",
"type": "Feature",
"properties": {
"t": [
1,
],
"s": [
1,
],
"Time": [
"2021-11-01",
]
},
"geometry": {
"type": "Point",
"coordinates": [
-1.881,
52.486
]
}
},
]
}
do I always need to create a model for an incoming JSON and then deserialize the JSON to it or is there a way to loop through the JSON file, check specific properties and add additional information?
Here is why I ask:
In my project I have two classes "region" and "country". Inside "region" is the nested class "country"
enter code here
public class Region`enter code here`
{
[Key]
public int Id { get; set; }
public string Region { get; set; }
public Country Country { get; set; }
}
public class Country
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(255)]
public string Name { get; set; }
[Required]
[MaxLength(2)]
public string ISO3166Alpha2 { get; set; }
[Required]
[MaxLength(3)]
public string ISO3166Alpha3 { get; set; }
}
Now I have an incoming JSON which has the country and region information which i need but without Ids or any other required information.
So do i need to create a new model, deserialize the JSON and then use that new model to create my "region" and "country" model or is there a better way of doing this?
{
"regions": [
{
"country": "France",
"region": [
"Bordeaux",
"Burgundy",
"Beaujolais",
"Champagne",
"Loire",
"Alsace",
"Rhône",
"Provence",
"Languedoc-Roussillon",
"Jura"
]
},
{
"country": "Italy",
"region": [
"Piedmont",
"Barolo",
"Barbaresco",
"Tuscany",
"Veneto",
"Friuli-Venezia",
"Giulia",
"Abruzzo",
"Sicily",
"Lambrusco"
]
}
}
´´´
Thanks a lot :)
kindly find below the way to achieve that as stated by the docs. kindly visit this link https://www.newtonsoft.com/json/help/html/DeserializeAnonymousType.htm but however my solution is shown below.
var json1 = #"{
'regions': [
{
'country': 'France',
'region': [
'Bordeaux',
'Burgundy',
'Beaujolais',
'Champagne',
'Loire',
'Alsace',
'Rhône',
'Provence',
'Languedoc-Roussillon',
'Jura'
]
},
{
'country': 'Italy',
'region': [
'Piedmont',
'Barolo',
'Barbaresco',
'Tuscany',
'Veneto',
'Friuli-Venezia',
'Giulia',
'Abruzzo',
'Sicily',
'Lambrusco'
]
}]}";
var definition = new { regions = new[]{new {country = "" , region = new string[]{ } } }};
var customer1 = JsonConvert.DeserializeAnonymousType(json1, definition);
Console.WriteLine(customer1.regions);
foreach (var item in customer1.regions)
{
Console.WriteLine(item.country);
}
I'm able to parse simple properties using JSON.NET with this C# code:
Code C#
WebClient c = new WebClient();
var data = c.DownloadString("http://localhost/json1.json");
JObject o = JObject.Parse(data);
listBox1.Items.Add(o["name"]);
listBox1.Items.Add(o["email"][0]);
listBox1.Items.Add(o["email"][1]);
listBox1.Items.Add(o["website"]["blog"]);
json1.json
{
"name": "Fname Lname",
"email": [
"email#gmail.com",
"email#hotmail.com"
],
"website":
{
"blog": "example.com"
}
}
json2.json
{
"name": "Fname Lname",
"email": [
"email#gmail.com",
"email#hotmail.com"
],
"website":
{
"blog": "example.com"
},
"faculty":
{
"department": [
{
"name": "department.name",
"location": "department.location"
}
]
}
}
From the second JSON file, I'm not able to get name and location from the department. How do I do that in C#?
name : department.name
location: department.location
yourjsonobject.faculty.department[0].name;
yourjsonobject.faculty.department[0].location;
Here is some jsfiddle to help you with this:
http://jsfiddle.net/sCCrJ/
var r = JSON.parse('{"name": "Fname Lname","email": [ "email#gmail.com", "email#hotmail.com"],"website":{ "blog": "example.com"},"faculty":{ "department": [ { "name": "department.name", "location": "department.location" } ]}}');
alert(r.faculty.department[0].name);
alert(r.faculty.department[0].location);
for (var i = 0; i < r.faculty.department.length; i++) {
alert(r.faculty.department[i].name);
}
Your problem is that department is an array of objects (though it happens to just contain one item here), but you're not accessing it like it is. You can use o["faculty"]["department"][0]["name"] to get your data.
You might want to use classes (here are ones auto-converted with http://json2csharp.com/) to more easily work with your data.
public class Website
{
public string blog { get; set; }
}
public class Department
{
public string name { get; set; }
public string location { get; set; }
}
public class Faculty
{
public List<Department> department { get; set; }
}
public class RootObject
{
public string name { get; set; }
public List<string> email { get; set; }
public Website website { get; set; }
public Faculty faculty { get; set; }
}
Then you can get all of the data (instead of hoping the fixed indexes are right, and that you didn't make a typo in the property names) with this code:
WebClient c = new WebClient();
var data = c.DownloadString("http://localhost/json1.json");
var o = JsonConvert.DeserializeObject<RootObject>(data);
listBox1.Items.Add(o.name);
foreach (var emailAddr in o.email)
listBox1.Items.Add(emailAddr);
listBox1.Items.Add(o.website.blog);
foreach (var dept in o.faculty.department)
{
listBox1.Items.Add(dept.name);
listBox1.Items.Add(dept.location);
}
I have such scheme of document:
{
"_id" : ObjectId("4fbb728d80db260988580e05"),
"titleFull" : "Foo, Inc",
"titleShort" : "Foo",
"countries" : [
ObjectId("4fba04ef80db260988f8b607"),
ObjectId("4fba05f880db260988cd5cfd") ],
"type" : "company"
}
And such class in ASP.NET MVC 4 Web API project:
public class Company
{
[BsonRepresentation(BsonType.ObjectId)]
public String id { get; set; }
public String titleFull { get; set; }
public String titleShort { get; set; }
//[BsonRepresentation(BsonType.ObjectId)]
//public String[] countries { get; set; } — not working
public ObjectId[] countries { get; set; }
public String type { get; set; }
}
When I'm sending GET request on /api/countries I receive JSON document (It's mvc deserialization):
{
"id": "4fba097e80db2609886ce7f2",
"titleFull": "Foo, LLC",
"titleShort": "Foo",
"countries": [
{
"_increment": 16299527
"_machine": 8444710
"_pid": 2440
"_timestamp": 1337591023
},
{
"_increment": 13458685
"_machine": 8444710
"_pid": 2440
"_timestamp": 1337591288
}
],
"type": "company"
}
Is there a way to do JSON response like this:
{
"id": "4fba097e80db2609886ce7f2",
"titleFull": "Foo, LLC",
"titleShort": "Foo",
"countries": ["4fba04ef80db260988f8b607","4fba05f880db260988cd5cfd"],
"type": "company"
}
Note to future readers
Rober Stam wrote in google groups:
There is a bug in the deserialization code. In the case of an array the [BsonRepresentation] attribute is in fact applied to the items and not the array.
I've created a JIRA ticket for this:
https://jira.mongodb.org/browse/CSHARP-479
So if you have the same issue, please track this ticket.
In the response instead of use ObjectId for Countries use a Array of string and add the ids that you want to pass in the json response.
public string[] countries { get; set; }
if you use like this the response will be something like this in json
"countries": ["4fba04ef80db260988f8b607","4fba05f880db260988cd5cfd"],
You are using a string already in the id field.