Writing JSON array in web API response - c#

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

Related

Send Correct Data Fetched to my Model via API

When I fetch data from my Basket API to further on post to my OrderLine API I get this back in JSON:
[
{
"productId": 1,
"quantity": 1
}
]
but my OrderLine API accepts the following:
{
"productId": 0,
"quantity": 0
}
I want to send the data fetched from my Basket API to my OrderLine so that the following is returned:
{
"orderID": 0,
"identifier": "string",
"customer": "string",
"items": [
{
"id": 0,
"productId": 0,
"quantity": 0
}
]
}
Where "items" is the data fetched from my Basket.
This is what my API GET Basket looks like for fetching data from basket:
// GET: https://localhost:5500/api/Basket/{identifier}
[HttpGet("/basket/{identifier}")]
public async Task<IEnumerable<OrderLineDTO>> GetBasketItems(string identifier)
{
var httpRequestMessage = new HttpRequestMessage(
HttpMethod.Get,
$"https://localhost:5500/api/Basket/{identifier}")
{
Headers = { { HeaderNames.Accept, "application/json" }, }
};
var httpClient = httpClientFactory.CreateClient();
using var httpResponseMessage =
await httpClient.SendAsync(httpRequestMessage);
var items = Enumerable.Empty<OrderLineDTO>();
if (!httpResponseMessage.IsSuccessStatusCode)
return items;
using var contentStream =
await httpResponseMessage.Content.ReadAsStreamAsync();
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var basketDto = await System.Text.Json.JsonSerializer.DeserializeAsync
<OrderDTO>(contentStream, options);
items = basketDto.Items.Select(x =>
new OrderLineDTO
{
ProductId = x.ProductId,
Quantity = x.Quantity,
}
);
var entryJson = new StringContent(
JsonSerializer.Serialize(items),
Encoding.UTF8,
Application.Json);
await httpClient.PostAsync($"http://localhost:5700/api/OrderLine", entryJson);
return items; // 200 OK
}
And this is my Post to OrderLine:
// POST: api/OrderLine
[HttpPost("/api/OrderLine")]
public async Task<ActionResult<Order>> PostOrderLine(OrderLine orderLine)
{
_context.OrderLine.Add(orderLine);
await _context.SaveChangesAsync();
return CreatedAtAction("GetOrder", new { id = orderLine.Id }, orderLine);
}
This is my OrderLineDTO:
public class OrderLineDTO
{
public int ProductId { get; set; }
public int Quantity { get; set; }
}
And this is my OrderLine model:
public class OrderLine
{
public int Id { get; set; }
public int ProductId { get; set; }
public int Quantity { get; set; }
}
Does anybody know how to solve this? Thanks in advance for any help, I'm just hoping to get the corresponding fetched data from my Basket API then send in back to OrderLine
EDIT:
Also added my OrderDTO which is callled upon in my GET Basket Method:
public class OrderDTO
{
public string Identifier { get; set; }
public string Customer { get; set; }
public List<OrderLine> Items { get; set; } = new List<OrderLine>();
}
You are returning items which is an object of type OrderLineDTO
What you want to return is an object of type OrderDTO

Create Serialize JSON List Type object from c# class

Dear All I am using C# Class and make the json object but how it call it.
and show the json object I am show the code please help me.
Here I am create a class
public class Contacts
{
public List<PhoneMobile> phoneMobiles { get; set; }
public List<PhoneLandline> phoneLandlines { get; set; }
public List<Email> emails { get; set; }
}
public class PhoneMobile
{
public string phoneMobile { get; set; }
}
Here i am use the class like this
contacts = new Contacts
{
phoneMobiles = new List<PhoneMobile>
{
},
phoneLandlines = new List<PhoneLandline>(),
emails = new List<Email>(),
}
I want SerializeObject Like This objects give how to put a value and make it.
"contacts": {
"phoneMobiles": [
{
"phoneMobile": "8103267511"
}
],
"phoneLandlines": [
{
"phoneLandLineNumber": "8103267511"
}
],
"emails": [
{
"email": "testing#gmail.com"
}
]
},
"contactPerson": [
{
"personName": "TEST KARKHANA",
"owner": "null",
"email": "sanjeet.kumar#mponline.gov.in",
"phone": "8602865989"
}
],
How To Make It Please Help
Use Json.Net library, you can download it from Nuget.
Try this
var contactCollection = new Contacts
{
phoneMobiles = new List<PhoneMobile>
{
new PhoneMobile { phoneMobile = "8103267511" }
},
phoneLandlines = new List<PhoneLandline>()
{
new PhoneLandline { phoneLandLineNumber = "8103267511" }
},
emails = new List<Email>()
{
new Email { email = "testing#gmail.com" }
}
};
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(contacts);
It will serialize object to json except contactPerson section
If you need serialize object with root name contacts then try
var collectionWrapper = new {
contacts = contactCollection
};
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(collectionWrapper);
then the result will be like:
{"contacts":{"phoneMobiles":[{"phoneMobile":"8103267511"}], "phoneLandlines":[{"phoneLandLineNumber":"8103267511"}], "emails":[{"email":"testing#gmail.com"}]}}

Parsing JSON with JObject

I need to parse a JSON, I am already parsing the first part of the record but I am having a problem with a sub record. This is my code:
List<JToken> results = new List<JToken>();
List<JToken> results2 = new List<JToken>();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
results = JObject.Parse(result).SelectToken("record").ToList();
}
List<Record> users = new List<Record>();
foreach (JObject token in results)
{
Record user = new Record();
user.id = Int32.Parse(token["id"].ToString());
user.full_name = token["full_name"].ToString();
user.email = token["email"].ToString();
//role.RoleName = token.SelectToken("name").ToString();
}
That's working perfectly but I have issues parsin a string that's a bit deeper. This is the JSON:
{
"record": [
{
"id": 2,
"institution_id": 1,
"full_name": "",
"email": "",
"role_id": 2,
"created": "2015-01-13 01:18:52.370379",
"updated": "2015-01-22 23:58:44.103636",
"branch_id": 1,
"Branch_by_branch_id": {
"id": 1,
"institution_id": 1,
"branch_name": "Test Branch"
}
}
]
}
I want to get the "branch_name" inside Branch_by_branch_id. How can I access it with Jobject?
If your JSON is this
{
"record": [
{
"id": 26,
"full_name": "",
"email": "",
"branch_id": 1,
"Branch_by_branch_id": {
"id": 1,
"institution_id": 1,
"branch_name": "NAME"
}
}
]
}
Have classes like this:
public class BranchByBranchId
{
public int id { get; set; }
public int institution_id { get; set; }
public string branch_name { get; set; }
}
public class Record
{
public int id { get; set; }
public string full_name { get; set; }
public string email { get; set; }
public int branch_id { get; set; }
public BranchByBranchId Branch_by_branch_id { get; set; }
}
public class RootObject
{
public List<Record> record { get; set; }
}
Then parse it and retrieve the value like this.
var root = JsonConvert.DeserializeObject<RootObject>(json);
var branchName = root[0].Branch_by_branch_id.branch_name;
I always prefer to access my JSON objects like this, because I like having my objects as native C# classes. The classes were generated by json2csharp.

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.

jQuery REST POST JSON List<Object>

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

Categories

Resources