Want to change JSON Format - c#

I have this class
public class Contact {
#regionContact Info
public Guid ContactID { get; set; }
public string Name { get; set; }
public string RegID { get; set; }
public string MobileNumber { get; set; }
public string Tel { get; set; }
#endregion
}
when I call getAllContact() method, I get this result
[{"ContactID":"7abe6291-43f2-e411-b150-000c2975315f","Name":"Visitor 1","RegID":"1","MobileNumber":"1122334455","Tel":"1122334455"},{"ContactID":"f76f310f-a3f3-e411-b150-000c2975315f","Name":"Visitor 2","RegID":"2","MobileNumber":null,"Tel":null},{"ContactID":"9b3e6018-a3f3-e411-b150-000c2975315f","Name":"Visitor 3","RegID":"3","MobileNumber":null,"Tel":null}]
but what I want is with this kind of format.
{"contacts":[{"ContactID":"7abe6291-43f2-e411-b150-000c2975315f","Name":"Visitor 1","RegID":"1","MobileNumber":"1122334455","Tel":"1122334455"},{"ContactID":"f76f310f-a3f3-e411-b150-000c2975315f","Name":"Visitor 2","RegID":"2","MobileNumber":null,"Tel":null},{"ContactID":"9b3e6018-a3f3-e411-b150-000c2975315f","Name":"Visitor 3","RegID":"3","MobileNumber":null,"Tel":null}]}
How can I change to get this json format? Could anybody help me please?

Your getAllContact() method should an object with one parameter in it called contacts which is of type List
public class ContactList {
public List<Contact> contacts { get; set; }
}
Then serialise the ContactList object.

Try to write like this way . sure u will get your result.Here i have added one item in list. you can add multiple items.
void getAllContact()
{
Dictionary<string, List<Contact>> contactsDic = new Dictionary<string, List<Contact>>();
List<Contact> list = new List<Contact>();
list.Add(new Contact
{
ContactID = Guid.Parse("7abe6291-43f2-e411-b150-000c2975315f"),
Name = "Visitor 1",
RegID = "1",
MobileNumber = "1122334455",
Tel = "1122334455"
}
);
contactsDic.Add("contacts", list);
string ss = JsonConvert.SerializeObject(contactsDic);
}

If your model is Contact class so Simplify do this:
return Ok(new {contacts = yourmodel});

Related

How to POST list of dictionaries

I would like to post following JSON via API using Restsharp library
{
"id" : "customerID",
"name" : "customerName",
"customKeys" : {
"dataA" : "{\"keyA\": \"valueA\", \"keyB\": \"valueB\"}",
"dataB" : "{\"keyA\": \"valueA\", \"keyB\": \"valueB\"}"
}
}
Actually i made following code which is creating Customer object and everything work correctly beside last fields customKeys....
public class Customer
{
public string id { get; set; }
public string name { get; set; }
public List<Dictionary<string, object>> customKeys { get; set; }
}
Customer customer = new Customer
{
id = id,
name = customerName,
customKeys = ????????????????
};
string json = JsonConvert.SerializeObject(customer);
RestRequest request = newRestRequest("someEndpoint",Method.POST);
request.AddJsonBody(customer);
var response = client.Execute(request);
I just wanted to be sure which data type i should use in following case.
Should i use Dictionary of Dictionaries or just ListOfDictionaries ? Or maybe there is a better and easier way to make that POST call ?
You would use a Dictionary of Dictionaries if your Dictionaries have a special meaning besides just positional placement.
Otherwise, you would be better with a List of Dictionaries.
You can try this:
public class CustomKeys
{
public string dataA { get; set; }
public string dataB { get; set; }
}
public class Customer
{
public string id { get; set; }
public string name { get; set; }
public List<CustomKeys> customKeys { get; set; }
}
Customer customer = new Customer
{
id = id,
name = customerName,
customKeys = new List<CustomKeys>()
{
dataA ="dataA",
dataB ="dataB "
};
};

unable to get list of elements in list

i have 2 model classes
public class ProductOptionRequest
{
public string Name { set; get; }
public List<ProductValuesRequest> productValues { get; set; }
}
public class ProductValuesRequest
{
public string ValueName { get; set; }
}
public class ProductOptionValue
{
public int OptionId { get; set; }
public String ValueName { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
}
and wrote one bs method and passing parameter value as value names. but I'm unable to get those values in a list object as productValues. May I know the solution, please.
public async Task<ReturnString> SaveProductOption(ProductOptionRequest request)
{
request.productValues = new List<ProductValuesRequest>();
foreach (ProductValuesRequest valueRequest in request.productValues)
{
ProductOptionValue res = new ProductOptionValue();
res.ValueName = valueRequest.ValueName;
object response = await productOptionValueRepository.InsertAsync(res, true);
}
}
In the first line of your method, you are replacing the productValues property of request object with a new empty list, :
request.productValues = new List<ProductValuesRequest>();
Therefore, in foreach loop, you are iterating on an empty list.
Remove the first line and see if you still have any issues.
You are assigning an emplty list to productValues as
request.productValues = new List() and trying to iterate the empty list.

Creating and populating an object with complex types

I'm working on an API that will ultimately return a data extract in JSON format. This isn't my exact code. I've simplified the idea so I can convey my question more clearly.
There's a method that queries the database and returns the following columns:
CustomerID, CustomerName, Preference, PreferenceValue (where one customer will have dozens of preferences). The dataset is ordered by CustomerID.
My goal is to return a JSON object like this:
{
"Customer": {
"CustomerID": "123",
"CustomerName": "John Smith",
"CustomerPreferences": {
"Color": "Red",
"Texture": "Rough",
"Size": "Medium",
"Weight": "Heavy"
}
}
}
I'm new to C# and OO. So, to these ends, I've been researching and trying various approaches all day. I can do this with a single object no problem, but not with a nested class. My intuition tells me what I'm trying to do shouldn't be much harder... but it continues to elude me.
I tried this (it didn't work). I made this class (note: it is the same shape as the JSON I'm hoping to get):
public class Customer
{
public string CustomerID { get; set; }
public string CustomerName { get; set; }
public class Preferences
{
public string Preference { get; set; }
public string PreferenceValue { get; set; }
}
}
Then I created the objects (although at this point, I'm already sure I'm on the wrong path, since I'm forced to initialize them separately):
List<Customer> lstCustomer = new List<Customer>();
List<Customer.Preference> lstPref = new List<Customer.Preference>();
Then I tried looping through my query results... (not sure why I'm still sharing this, since I know it doesn't work, and I'm likely embarrassing myself!!):
if (rdr.HasRows)
{
string CurrentCustomer = "";
while (rdr.Read())
{
/*
Since the data is sorted by CustID,
I only add the parent class when it changes.
*/
if (CurrentCustomer != rdr["CustID"].ToString())
{
lstCustomer.Add(new Customer
{
CustomerID = rdr["CustID"].ToString(),
CustomerName = rdr["CustomerName"].ToString()
});
CurrentCustomer = rdr["CustID"].ToString();
}
lstPref.Add(new Customer.Preference
{
PrefName = rdr["PreferanceName"].ToString(),
PrefValue = rdr["PreferenceValue"].ToString()
});
}
}
I have the feeling this is relatively easy. I've been searching and searching, and cannot find the solution. Once I have an object created and populated, returning it as JSON is a snap. But I can't figure out how to create this simple data structure!
You're not that far off. I'd go with something like this
public class Customer
{
public string CustomerID { get; set; }
public string CustomerName { get; set; }
public Dictionary<string, string> Preferences { get; set; }
public Customer()
{
Preferences = new Dictionary<string, string>();
}
}
and
List<Customer> customers = new List<Customer>();
if (rdr.HasRows)
{
Customer CurrentCustomer = new Customer();
while (rdr.Read())
{
/*
Since the data is sorted by CustID,
I only add the parent class when it changes.
*/
if (CurrentCustomer.CustomerID != rdr["CustID"].ToString())
{
CurrentCustomer = new Customer()
{
CustomerID = rdr["CustID"].ToString(),
CustomerName = rdr["CustomerName"].ToString()
};
customers.Add(CurrentCustomer);
}
CurrentCustomer.Preferences.Add(rdr["PreferanceName"].ToString(),
rdr["PreferenceValue"].ToString());
}
}
but try not to butcher the formatting like I did ...
It seems to me your JSON structure and your class structure don't really match. Instead of a nested class, consider using a dictionary to match a preference name to its value.
public class Customer
{
public string CustomerID { get; set; }
public string CustomerName { get; set; }
public Dictionary<string, string> Preferences { get; }
}
Then you can add preferences to your dictionary using the usual add method.
Move preferences outside of your Customer class, and define a property instead:
public class Customer
{
public string CustomerID { get; set; }
public string CustomerName { get; set; }
public List<Preference> Preferences { get; set;}
}
public class Preference
{
public string Preference { get; set; }
public string PreferenceValue { get; set; }
}

ASP.NET add items to List from Class

I have this class here:
public class CP_VIP_Preview_TimeSlots
{
public int id { get; set; }
[DisplayName("Time Slots")]
public string timeSlot { get; set; }
[DisplayName("Date Slots")]
public string dateSlot { get; set; }
}
public class CPVIPPreviewTimeSlots : DbContext
{
public DbSet<CP_VIP_Preview_TimeSlots> Data { get; set; }
}
Now what I am trying to do is put each item of the class into a List, I have created this list:
List<string> newList = new List<string>();
What I am looking to add to this list is a the id and timeSlot and DateSlot, however I want the timeSlot and DateSlot as a combined string. So my new list will have id and some string called timeDateSlot...I hope this make sense, how would I do this?
If you have a CP_VIP_Preview_TimeSlots called test:
newList.add(test.id.ToString());
newList.add(test.timeSlot + test.dateSlot);
However, you do not get to choose identifiers for these string.
If you really don't want to store a list of your TimeSlots class then what you need is a list of KeyValuePairs.
List<KeyValuePair<int,string>>
and in this you can add:
List<KeyValuePair<int,string>> myList = new List<KeyValuePair<int,string>>();
myList.Add(new KeyValuePair<int, string>(test.id.ToString(), test.timeSlot + test.dateSlot));
List<CP_VIP_Preview_TimeSlots> newList = new List<CP_VIP_Preview_TimeSlots>();
foreach(var x in CPVIPPreviewTimeSlots){ //whatever your db data is
newList.add(x); //add an instance to list
}
Something like this might help. Then you could display like so,
var x = newList.first();
string combined = x.timeSlot + x.dateSlot;
You can add an extra property to your class to get the correct string that is accessible anywhere:
public class CP_VIP_Preview_TimeSlots
{
public int id { get; set; }
[DisplayName("Time Slots")]
public string timeSlot { get; set; }
[DisplayName("Date Slots")]
public string dateSlot { get; set; }
public string combinedString
{
get
{
return timeSlot + " " + dateSlot;
}
}
}
This can then also be used in your other question
DropDownList1.DataSource = newList;
DropDownList1.DataTextField = "combinedString";
DropDownList1.DataValueField = "timeSlot";
DropDownList1.DataBind();
If you want to identify data using Id you can use the following code
foreach(CP_VIP_Preview_TimeSlots d in CPVIPPreviewTimeSlots.Data)
{
List<KeyValuePair<int,string>> lstIdWiseData = new List<KeyValuePair<int,string>>();
lstIdWiseData.Add(new KeyValuePair<int,string>(d.Id, string.Concat(d.timeSlot, d.dateSlot )));
}
If your id is not unique you can replace KeyValuePair<int,string> with Tuple<int,string> in the above code

C# Copy List items to Object Arrays

I have a list created from a stored procedure using EF6.0
I have also created 3 classes
public class Resas
{
public string todo{ get; set; }
public string prop { get; set; }
public string Code { get; set; }
public string statusCode { get; set; }
public string checkin { get; set; }
public string checkout { get; set; }
public List<profiles> profiles { get; set; }
}
public class profiles
{
public string action { get; set; }
public string id { get; set; }
public string profileType { get; set; }
public string title { get; set; }
public string firstName { get; set; }
public string middleName { get; set; }
public string lastName { get; set; }
public List<emailAddresses> emailAdresses { get; set; }
}
public class emailAddresses
{
public string emailAddress { get; set; }
public string emailAddress2 { get; set; }
}
I am doing a for-loop in the list and I need to get certain columns and put it in the array (I will put two, to keep it simple)
myEntities db = new myEntities();
List<rev_Result> revList = new List<rev_Result>();
revList.Clear();
revList = db.rev().ToList();
for (int i = 0; i < revList.Count(); i++)
{
Resas resas = new Resas();
profiles[] profiles = new profiles[1];
resas.todo = revList[i].todo;
resas.profiles[0].lastName = revList[i].lastName;
}
I am not familiar with C# as you can see from the psedo-code above.
I cannot figure out how to feed the Resas with data and then its Profile with data and then move to the next Resas entry.
Any help appreciated.
That's fairly simple using Linq:
Resas resas = new Resas();
resas.profiles = revList
.Select(x => new profiles() { action = x.todo, lastName = x.lastName })
.ToList();
What's happening here is: You loop through every entry in revList and get your wanted data structure (that's what Select is doing). x refers to the current entry in the loop, while the stuff to the right side of the arrow is you 'output': a new instance of your profiles class with the members assigned accordingly. The result of all of this is then converted to a list (before ToList(), think of it as a recipe to create the list) and assigned to resas.profiles.
By the way, a word on conventions: Usually, in C#, you would give your classes a name that starts with a capital letter. Also, your profiles class seems to contain data of exactly one profile, so a better name might be Profile. This also makes your data structure more clear, since List<profiles> seems to be a list of lists of profiles - but that's not what it actually is, is it?
Furthermore, Members generally start with a capital letter as well, so instead of action, lastName, you'd have: Action and LastName.
You can try with Linq. This is the code that should solve your issue, but Resas class doesn't have action property:
List<Resas> ls = revList.Select(x => new Resas() {
action = x.todo,
profiles = new List<profiles>() {
new profiles { lastName = x.lastName }
}
).ToList();
If you need to use action property of inprofiles` class:
List<Resas> ls = revList.Select(x => new Resas() {
profiles = new List<profiles>() {
new profiles {
action = x.todo,
lastName = x.lastName
}
}
).ToList();

Categories

Resources