I am trying to create generic class that will map or flatten an object.
Lets say i have this 2 classes
public class Description
{
public string Info { get; set; }
}
public class Item
{
public string Title { get; set; }
public int WordsCount { get; set; }
public string Url { get; set; }
public List<string> Headers { get; set; }
public User Owner { get; set; }
public List<Description> Descriptions { get; set; }
}
I try to create something like this:
Item item = new Item()
{
Url = "http",
Title = "home page",
Details = new Description() { Info = "some info" },
WordsCount = 220,
Headers = new List<string>() { "One", "Two", "Three" },
Descriptions = new List<Descriptions>()
{
new Description() { Info = "info 1" },
new Description() { Info = "info 2" },
new Description() { Info = "info 3" },
}
};
After the flattening/mapping i want to have something like:
Item {
Url: 'http',
Title: 'home page',
Details.Info: 'some info',
WordsCount: '220',
Headers: 'One^Two^Three',
Descriptions.0.Info: 'info 1'.
Descriptions.1.Info: 'info 2',
Descriptions.2.Info: 'info 3',
}
I tried with AutoMapper but i guess i am not able to achieve this
Any suggestions?
Related
In API controller, I am trying to map manually author's list of article to the corresponding modelDTO. I am using the model class AuthorDTO and NewsContentDTO to list author details and his corresponding articles. Looking for someone help to map all NewContents of an author from linq result to AuthorDTO and to return AuthorDTO with the details of an author and its corresponding all news contents. How can I poppulate NewsContents in AuthorDTO from the result coming from GetHeroAuthor()
public class AuthorDTO
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public List<NewsContentDTO> NewsContents { get; set; }
}
public class NewsContentDTO
{
public int Id { get; set; }
public string Category { get; set; }
public string ContentTitle { get; set; }
public AuthorDTO Author { get; set; }
}
In API controller
var authors = _authorRepo.GetHeroAuthor();
AuthorDTO author = new AuthorDTO()
{
FirstName = authors.FirstName,
LastName = authors.LastName
NewsContents = New List<NewsContentDTO>()
{
Category = authors.NewsContents.Category,
ContentTitle = authors.NewsContents.ContentTitle
}
};
return(author);
List of Records is coming from repo
{
"id": 2,
"firstName": "My",
"lastName": "Name",
"newsContents": [
{
"id": 2,
"category": "Story",
"contentTitle": "Shopping Trip",
},
{
"id": 3,
"category": "Story",
"contentTitle": "Rainy day",
}
]
}
As you've not explicitly provided a question I presume your challenge is mapping a list of subitems.
AuthorDTO author = new AuthorDTO()
{
FirstName = authors.FirstName,
LastName = authors.LastName
// THIS WON'T WORK
NewsContents = New List<NewsContentDTO>()
{
Category = authors.NewsContents.Category,
ContentTitle = authors.NewsContents.ContentTitle
}
// TO MAP A SOURCE LIST TO TARGET LIST, TRY THIS ...
NewsContents = authors.NewsContents.Select(nc => new NewsContentDTO()
{
Category = nc.Category,
ContentTitle = nc.ContentTitle
}).ToList();
};
I'm having an Model Class, I need to Save it in a MongoDB Collection.
My Model Class:
public Class Employee
{
public string EmpID { get; set; }
public string EmpName { get; set; }
public List<Mobile> EmpMobile { get; set; }
}
public Class Mobile
{
public string MobID { get; set; }
public string MobNumber { get; set; }
public bool IsPreferred { get; set; }
}
The Values are
Employee EmpInfo = new Employee()
{
EmpID = "100",
EmpName = "John",
EmpMobile = new List<Mobile>()
{
{ MobNumber = "55566610", IsPreferred = true },
{ MobNumber = "55566611", IsPreferred = false },
}
}
BsonDocument _employee = new BsonDocument()
{
{ "Emp_ID", EmpInfo.EmpID },
{ "Emp_Name", EmpInfo.EmpName },
{ "Emp_Mobile", new BsonArray (EmpInfo.EmpMobile.Select(m => new
{
MobID = new ObjectId(),
MobNumber = m.MobNumber,
IsPreferred = m.IsPreferred
})) }
};
var collection = _database.GetCollection<BsonDocument>("EmployeeInfo");
collection.InsertOne(_employee);
I wish to save the above EmpInfo of type Employee in a MongoDB. But I can't able to create a BsonDocument. Kindly assist me is there is anything wrong in the above code. If yes kindly assist me.
there is no need to serialize to bson document
You can use TYPED collection and just insert data
Please see attached code snipet with updated class structure
void Main()
{
// To directly connect to a single MongoDB server
// or use a connection string
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("test");
var collectionEmpInfo = database.GetCollection<Employee>("Employee");
Employee EmpInfo = new Employee
{
EmpID = "100",
EmpName = "John",
EmpMobile = new List<Mobile>
{
new Mobile{ MobNumber = "55566610", IsPreferred = true, MobID = ObjectId.GenerateNewId() },
new Mobile{ MobNumber = "55566611", IsPreferred = false, MobID = ObjectId.GenerateNewId() },
}
};
collectionEmpInfo.InsertOne(EmpInfo);
var empList = collectionEmpInfo.Find(new BsonDocument()).ToList();
empList.Dump(); //dump is used in linqPad
}
public class Employee
{
public ObjectId Id { get; set; }
public string EmpID { get; set; }
public string EmpName { get; set; }
public List<Mobile> EmpMobile { get; set; }
}
public class Mobile
{
public ObjectId MobID { get; set; }
public string MobNumber { get; set; }
public bool IsPreferred { get; set; }
}
In addition to answer above, I can suggest following code if you want to deal directly with Bson for some reason:
BsonDocument _employee = new BsonDocument()
{
{ "Emp_ID", EmpInfo.EmpID },
{ "Emp_Name", EmpInfo.EmpName },
{ "Emp_Mobile", BsonArray.Create(EmpInfo.EmpMobile.Select(m => new BsonDocument()
{
{ "MobID" , new ObjectId() },
{ "MobNumber", m.MobNumber },
{ "IsPreferred", m.IsPreferred }
})) }
};
The reason of the error you've got is that BsonArray.Create creates an array of values, not an array of objects. See this question for details.
My JSON looks like this:
[
{
"id": 001,
"name": "Item 1",
"tree": [
"010",
"020",
"030"
]
},
{
"id": 002,
"name": "Item 2",
"tree": [
"010",
"020",
"030"
]
},
{
"id": 003,
"name": "Item 3",
"tree": [
"010",
"020",
"030"
]
}
]
This can be modelled into C# as following:
public class Product
{
public int id { get; set; }
public string name { get; set; }
public List<string> tree { get; set; }
}
I'm trying to display this JSON data into a TreeListView in the ObjectListView libary. Ideally, it would look like this.
My current code is as following, with "data" being the TreeListView.
List<Product> Products = JsonConvert.DeserializeObject<List<Product>>(json);
data.CanExpandGetter = model => ((Product)model).tree.Count > 0;
data.ChildrenGetter = delegate(object model)
{
return ((Product)model).
tree;
};
data.SetObjects(Products);
However, this throws an System.InvalidCastException at model => ((Product)model).tree.Count > 0.
I found the solution. I changed the JSON layout a bit.
public class ProductJSON
{
public string id { get; set; }
public string name { get; set; }
public List<Tree> tree { get; set; }
}
public class Tree
{
public string id { get; set; }
public string name { get; set; }
}
public class Product
{
public string id { get; set; }
public string name { get; set; }
public List<Product> tree { get; set; }
public Product(string _id, string _name)
{
id = _id;
name = _name;
tree = new List<Product>();
}
}
...
List<ProductJSON> Products = JsonConvert.DeserializeObject<List<ProductJSON>>(json);
List<Product> ProductList = new List<Product>();
for(int i = 0; i < Products.Count; i++)
{
ProductList.Add(new Product(Products[i].id, Products[i].name));
foreach (Tree t in Products[i].tree)
{
ProductList[i].tree.Add(new Product(t.id, t.name));
}
}
data.CanExpandGetter = delegate(object x) { return true; };
data.ChildrenGetter = delegate(object x) { return ((Product)x).tree; };
cID.AspectGetter = delegate(object x) { return String.Format("{0,3:D3}", ((Product)x).id); };
cName.AspectGetter = delegate(object x) { return ((Product)x).name; };
data.Roots = ProductList;
I'm having the following classes on C#:
public class Record
{
public Record()
{
this.Artists = new List<Artist>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public List<Artist> Artists { get; set; }
}
public class Artist
{
public Artist()
{
this.Songs = new List<Song>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Album { get; set; }
public List<Song> Songs { get; set; }
}
public class Song
{
public Song()
{
}
public int Id { get; set; }
public string Name { get; set; }
}
Then we add some data:
Record record = new Record();
record.Id = 1;
record.Name = "Some music";
record.Description = "Something...";
Artist artist = new Artist();
artist.Id = 1;
artist.Name = "Bob Marley";
artist.Album = "Legend";
Song song = new Song();
song.Id = 1;
song.Name = "No woman no cry";
artist.Songs.Add(song);
song = new Song();
song.Id = 2;
song.Name = "Could you be loved";
artist.Songs.Add(song);
record.Artists.Add(artist);
artist = new Artist();
artist.Id = 2;
artist.Name = "Major Lazer";
artist.Album = "Free the universe";
song = new Song();
song.Id = 2;
song.Name = "Get free";
artist.Songs.Add(song);
song = new Song();
song.Id = 2;
song.Name = "Watch out for this";
artist.Songs.Add(song);
record.Artists.Add(artist);
string jsonVal = JsonConvert.SerializeObject(record);
textBox1.Text = jsonVal;
The last 2 lines will serialize the record type object to JSON using Newtonsoft Json and here is the resulted JSON:
{"Id":1,"Name":"Some music","Description":"Something...","Artists":[{"Id":1,"Name":"Bob Marley","Album":"Legend","Songs":[{"Id":1,"Name":"No woman no cry"},{"Id":2,"Name":"Could you be loved"}]},{"Id":2,"Name":"Major Lazer","Album":"Free the universe","Songs":[{"Id":2,"Name":"Get free"},{"Id":2,"Name":"Watch out for this"}]}]}
Now I need to create this JSON using javascript and POST that json to WEB API endpoint. What I don't know is how to create the object in javascript.
I know there is JSON.stringify(object) that will serialize the object, but how can I create the List ???
I know I can do something like this:
var record =
{
Name: "Whatever",
Description: "Something else",
//How can I make the List<object>
};
I'm thinking about array and probably this is the right one ... something like this:
var record =
{
Name: "Whatever",
Description: "Something else",
Artists:
{
"Name": "Artist Name",
"Album": "Some Album".
"Songs":
{
"Name": "SongName"
}
},
};
and last:
JSON.stringify(record);
You should use a JavaScript Array for a .NET collection.
var record = {
name: "Whatever",
description: "Something else",
artists: [{
name: "Artist Name",
album: "Some Album",
songs: [{
name: "Some Song"
}]
}]
};
Web API will treat the JSON as case insensitive.
You need to use this code for jQuery REST POST JSON List
var jsonObj = [];
$.each({ name: "John", lang: "JS" }, function (key,value) {
jsonObj.push(
{
key: value
});
});
I have the following class:
public partial class Content
{
public int ContentId { get; set; }
public int ContentTypeId { get; set; }
public string Title { get; set; }
public string Text { get; set; }
public System.DateTime ModifiedDate { get; set; }
public virtual byte[] Version { get; set; }
public int SubjectId { get; set; }
public virtual Subject Subject { get; set; }
}
and the following code:
var myData = new[] {
"Content 1",
"Content 2",
"Content 3"
};
var contents = myData.Select(e => new Content
{
Title = e,
Text = "xx",
ModifiedDate = DateTime.Now
}
How can I modify this so I can specify both the "Title" and some small sample "Text" in the myData array. I was thinking about using an array of objects but I am not quite sure how to set this up.
Here is the syntax for that:
var myData = new List<Content>
{
new Content{Title = "Content 1", Text = "xx", ModifiedDate = DateTime.Now},
new Content{Title = "Content 2", Text = "AB", ModifiedDate = DateTime.Now},
new Content{Title = "Content 3", Text = "CC", ModifiedDate = DateTime.Now}
};
How about you use Tuple?
var myDatas = new[]
{
new Tuple<string, string, DateTime>("Title", "Example", DateTime.Now),
new Tuple<string, string, DateTime>("Title2", "Example", DateTime.Now.AddDays(-1)),
new Tuple<string, string, DateTime>("Title3", "Example", DateTime.Now.AddDays(1))
};
var contents = myDatas.Select(e => new Content
{
Title = e.Item1,
Text = e.Item2,
ModifiedDate = DateTime.Now
});