jQuery REST POST JSON List<Object> - c#

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
});
});

Related

Writing JSON array in web API response

Need a JSON response like this:
{
"statusCode": 200,
"errorMessage": "Success",
"Employees": [
{
"empid": "7228",
"name": "Tim",
"address": "10815 BALTIMORE",
},
{
"empid": "7240",
"name": "Joe",
"address": "10819 Manasas",
}
]
}
Model Class:
public class EmployeeList
{
public string empid { get; set; }
public string name { get; set; }
public string address { get; set; }
}
public class Employee
{
public int statusCode { get; set; }
public string errorMessage{ get; set; }
public List<EmployeeList> Employees { get; set; }
}
Controller is like this:
List<Models.Employee> emp = new List<Models.Employee>();
//call to SP
if (rdr.HasRows)
{
var okresp = new HttpResponseMessage(HttpStatusCode.OK)
{
ReasonPhrase = "Success"
};
Models.Employee item = new Models.Employee();
{
item.statusCode = Convert.ToInt32(okresp.StatusCode);
item.errorMessage = okresp.ReasonPhrase;
while (rdr.Read())
{
item.Employees = new List<EmployeeList>{
new EmployeeList
{
empid = Convert.ToString(rdr["empid"]),
name = Convert.ToString(rdr["name"]),
address = Convert.ToString(rdr["address"])
}};
}
};
emp.add(item);
// return response
What should be my controller class code to create JSON array response while I read data from reader?
I am not able to get the loop part of creating JSON array in response file. Am I assigning the values in While loop incorrectly?
After your while (rdr.Read()), you reset item.Employees with a new List<EmployeeList> at every data. So you will be getting the last element every time.
Move your list initialisation outside of the loop and use the add method.
item.Employees = new List<EmployeeList>();
while (rdr.Read())
{
item.Employees.Add(
new EmployeeList
{
empid = Convert.ToString(rdr["empid"]),
name = Convert.ToString(rdr["name"]),
address = Convert.ToString(rdr["address"])
});
}

How to Convert List<T> to BsonArray to save a MongoDB Document

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.

Flatten or Map objects in C#

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?

How to Get Values from a json response string in C#

I want to get "id" "gender", "name", "picture" from a this json response string
{
"data": [{
"name": "XXX",
"gender": "male",
"id": "528814",
"picture": {
"data": {
"is_silhouette": false,
"url": "https:\/\/fbcdn-profile-a.akamaihd.net\/hprofile-ak-frc3\/v\/t1.0-1\/p50x50\/551182_10152227358459008__n.jpg?oh=983b70686285c2f60f71e665ace8ed5f&oe=54C1220C&__gda__=1422017140_998fbe013c4fe191ccadfdbc77693a76"
}
}
}
string[] data = friendsData.Split(new string[] { "}," }, StringSplitOptions.RemoveEmptyEntries).ToArray();
foreach (string d in data)
{
try
{
FacebookFriend f = new FacebookFriend
{
id = d.Substring("\"id\":\"", "\""),
gender = d.Substring("gender\":\"", "\""),
name = d.Substring("name\":\"", "\""),
picture = d.Substring("\"picture\":{\"data\":{\"url\":\"", "\"").Replace(#"\", string.Empty)
};
FacebookFriendList.Add(f);
}
catch
{
continue;
}
}
This code looks bad if the json data changes then you need to modify your logic accordingly. I would suggest you to serialize and deserialize the model data using Json serialization.
Model:
public class SerializationModel
{
public Data Data { get; set; }
}
public class Data
{
public string Name { get; set; }
public string Gender { get; set; }
public string Id { get; set; }
public Picture Picture { get; set; }
}
public class Picture
{
public PictureData Data { get; set; }
}
public class PictureData
{
public bool is_silhouette { get; set; }
public string url { get; set; }
}
Serialize your data to get the json output is like,
SerializationModel serializationModel = new SerializationModel
{
Data = new Data
{
Gender = "mALE",
Id = "88",
Name = "User",
Picture = new Picture
{
Data = new PictureData
{
is_silhouette = true,
url = "www.google.com"
}
}
}
};
string serializedString = Newtonsoft.Json.JsonConvert.SerializeObject(serializationModel);
which would yield the below result,
{"Data":{"Name":"User","Gender":"mALE","Id":"88","Picture":{"Data":{"is_silhouette":true,"url":"www.google.com"}}}}
To deserialize the json data back to the model,
SerializationModel sm = Newtonsoft.Json.JsonConvert.DeserializeObject<SerializationModel>(serializedString);
Then you can get the required values from the model itself.

how to create a json format using json.net in c#

I need a final json format as follows and that should be dynamic.
{
"product_items" :
[
{
"_at" : 1,
"product_id" : "999"
},
{
"_at" : 2,
"quantity" : 2.00
},
{
"_delete_at" : 3
}
]
}
How to create a json format as above in the code._at field is dynamic.sometimes it might be 2 and sometimes it might be 10.I dont have idea on to generate the json dynamically in c#.
class Test
{
public ProductItem[] product_items { get; set; }
class ProductItem
{
public int[] _at { get; set; }
public int[] _delete { get; set; }
public int[] quantity { get; set; }
public string[] product_id{get;set;}
}
}
i have create the the properties for json as above.
I'm using Newtonsoft library
Your class should look more like this:
public class ProductItem
{
public int _at { get; set; }
public string product_id { get; set; }
public double? quantity { get; set; }
public int? _delete_at { get; set; }
}
public class ProductItemObject
{
public List<ProductItem> product_items { get; set; }
}
A example on serializing :
List<ProductItem> list = new List<ProductItem>();
ProductItemObject o = new ProductItemObject { product_items = list };
var item1 = new ProductItem { _at = 1, product_id = "001" };
var item2 = new ProductItem { _at = 2, quantity = 2.00 };
var item3 = new ProductItem { _delete_at = 3 };
list.Add(item1);
list.Add(item2);
list.Add(item3);
string json = JsonConvert.SerializeObject(o, Formatting.Indented);
// json string :
// {
// "product_items": [
// {
// "_at": 1,
// "product_id": "001",
// "quantity": null,
// "_delete_at": null
// },
// {
// "_at": 2,
// "product_id": null,
// "quantity": 2.0,
// "_delete_at": null
// },
// {
// "_at": 0,
// "product_id": null,
// "quantity": null,
// "_delete_at": 3
// }
// ]
//}
An alternative full dynamic that gets u the same Json string without any model :
var jsonObject = new JObject();
dynamic objectList = jsonObject;
objectList.product_items = new JArray() as dynamic;
dynamic item = new JObject();
item._at = 1;
item.product_id = "999";
objectList.product_items.Add(item);
item = new JObject();
item._at = 2;
item.quantity = 2.00;
objectList.product_items.Add(item);
item = new JObject();
item._delete_at = 3;
objectList.product_items.Add(item);
string json = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObject, Formatting.Indented);
Well, if I understand you properly and you just need to be able to generate that json, the product list should be dynamic with maybe anonymous classes then:
public class Products
{
public Products()
{
product_items = new List<dynamic>();
}
public List<dynamic> product_items { get; set; }
}
products.product_items.Add(new { _at = 1, product_id = "999" });

Categories

Resources