Postman return empty Json result web api - asp.net-core-webapi

I have created the employee.json which will have id,firstname and lastname i am try to get the json reponse back, but postman return me an empty json object
[Route("api/[controller]")]
[ApiController]
public class EmployeeController : ControllerBase
{
public JsonResult Get()
{
var jsonFile = System.IO.File.ReadAllText(#"C:\Users\Employee.json");
List<Employee> employee = JsonConvert.DeserializeObject<List<Employee>>(jsonFile);
return new JsonResult(new Employee(1, "Toyota", "Aygo"));
}
}
here is the employee.json file
[{
"id": 1,
"firstname": "First Employee First Name",
"lastname": "First Employee Last Name"
},
{
"id": 2,
"firstname": "Second Employee First Name",
"lastname": "Second Employee Last Name"
}]
Below is the Postman response

Check the name of your file Employee.json not employee.json
which should be same as codes in controller.
Set Employee Model as below
public class Employee
{
public Employee(int id, string firstname, string lastname)
{
this.Id = id;
this.FirstName = firstname;
this.LastName = lastname;
}
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Codes of Controller
[Route("api/[controller]")]
[ApiController]
public class EmployeeController : ControllerBase
{
public JsonResult Get()
{
var jsonFile = System.IO.File.ReadAllText(#"D:\Users\Employee.json");
List<Employee> employee = JsonConvert.DeserializeObject<List<Employee>>(jsonFile);
//return new JsonResult(new Employee(1, "Toyota", "Aygo"));
return new JsonResult(employee);
}
}
Result

Related

LINQ query to select inner list only(Issue in JSON response)

I am facing issue in LINQ query, basically, it not returning records as per required format of JSON. I have two entity Users and And Address both have foreign key relation.
I have 2 entity as below
public class Users
{
public int Id { set; get; }
public string FName { set; get; }
public string LName { set; get; }
public string UserName { set; get; }
public string Password { set; get; }
public ICollection<Address> Address{ set; get; }
public string Contact { set; get; }
public decimal Salary { set; get; }
public string xyz { set; get; }
}
public class Address
{
public int AddressID { set; get; }
public string Address1 { set; get; }
public string Address2 { set; get; }
public string City { set; get; }
}
Context Class
public class MyContext : DbContext
{
public MyContext(DbContextOptions<MyContext> options): base(options)
{
}
public DbSet<Users> Users { get; set; }
}
API
[HttpGet("getaddressbyuser/{userId}")]
[Route("getaddressbyuser")]
public async Task<ActionResult<List<ICollection<Address>>>> GetAddressByUser(int userId)
{
var addr = await _context.Users.Where(x => x.Id == userId).Select(y => y.Address).ToListAsync();
if (addr == null)
{
return NotFound();
}
return addr;
}
When I called the API
http://localhost:55433/api/Users/getaddressbyuser/2
It' returns the following json
[
[
{
"addressID": 1,
"address1": "Noida",
"address2": "Noida 201301",
"city": "Noida"
},
{
"addressID": 2,
"address1": "Noida",
"address2": "Noida 201301",
"city": "Noida"
}
]
]
While I wnat to records as below
[
{
"addressID": 1,
"address1": "Noida",
"address2": "Noida 201301",
"city": "Noida"
},
{
"addressID": 2,
"address1": "Noida",
"address2": "Noida 201301",
"city": "Noida"
}
]
Note: I am using DotNet Core 2.2, Thanks
var addr = await _context.Users.Where(x => x.Id == userId).SelectMany(y=>y.Address).ToListAsync();
The problem is with select. Address is a list thus you need to use select many to flatten the results. In your select statement you tell him from a list of users select for each user their adresses so you have a list of users where each user has a list of addresses. So the it's not JSON problem or anything. If you use debuggger you will see that in C# it's a list containing lists. Plus considering that you want this JSON your return type is incorrect. Simply use IEnumarable<Address>
Change your return type.
Try with type <List<Address>>
If you want to use ICollection you can use only ICollection<Address>

How do i serialize a JSchema as part of another object?

I have an object who as a property that is a Json Schema (JSchema).
JSchema aSchema;
object foo = new {propA = "x", schema = aSchema};
However, when this is serialized:
string str = JsonConvert.SerializeObject(foo);
The JSchema object is serialized along with all its other properties ... and not a clean Json Schema, like the output of its ToString() which just emits the Json Schema string.
What I want is the schema property serialized as a Json Schema object like this:
{
"propA": "x",
"schema": {
"id": "",
"description": "",
"definitions": {
"number": {
"type": "number"
},
"string": {
"type": "string"
}
},
"properties": {
"title": {
"title": "Title",
"type": "string"
}
}
}
}
How would you do this?
public class Number
{
public string type { get; set; }
}
public class String
{
public string type { get; set; }
}
public class Definitions
{
public Number number { get; set; }
public String #string { get; set; }
}
public class Title
{
public string title { get; set; }
public string type { get; set; }
}
public class Properties
{
public Title title { get; set; }
}
public class Schema
{
public string id { get; set; }
public string description { get; set; }
public Definitions definitions { get; set; }
public Properties properties { get; set; }
}
public class RootObject
{
public string propA { get; set; }
public Schema schema { get; set; }
}
Serialize method
dynamic coll = new
{
Root = new RootObject()
{
propA = "x",
schema = new Schema
{
id = "",
description = "",
definitions = new Definitions()
{
number = new Number()
{
type = "number"
},
#string = new String()
{
type = "number"
}
},
properties = new Properties ()
{
title = new Title ()
{
title = "Title",
type = "string"
}
}
}
}
};
var output = JsonConvert.SerializeObject(coll);
Fiddler: https://dotnetfiddle.net/f2wG2G
Update
var jsonSchemaGenerator = new JsonSchemaGenerator();
var myType = typeof(RootObject);
var schema = jsonSchemaGenerator.Generate(myType);
schema.Id = "";
schema.Description = "";
schema.Title = myType.Name;
Fiddler: https://dotnetfiddle.net/FwJX69

ASP.NET & Json - simple hierarchy

I have a simple ASP.NET Class with 4 properties. What I'd like to to is package this class into a JSON string and add a "data" parent at the top level. What's the best way to add in the "data" element at the top level?
using Newtonsoft.Json;
[DataContract]
public class Task
{
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "notes")]
public string Notes { get; set; }
}
static void Main(string[] args)
{
var task = new Task();
task.Name = "Test Task";
task.Notes = "Test task created by ASP.NET";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://example.com/api");
HttpResponseMessage response = client.PostAsJsonAsync<Task>("tasks", task).Result;
response.EnsureSuccessStatusCode();
string responseBody = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(responseBody);
Console.ReadLine();
}
The Json I am getting back from this code is the following:
{
"name": "Test Task",
"notes": "Test task created by ASP.NET",
}
What I'd like is the following:
{
"data": {
{
"name": "Test Task",
"notes": "Test task created by ASP.NET",
}
}
You could create a simple dictionary:
public class Task
{
public Task
{
Data = new Dictionary<string,string>();
}
[DataMember(Name = "data")]
public Dictionary<string,string> Data { get; private set; }
}
Populate like:
Task t =new Task();
t.Data.Add("name","test task");
t.Data.Add("notes","teet");
Yes you could create another class and embed it like this also:
public class Data
{
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "notes")]
public string Notes { get; set; }
}
public class Task
{
public Task
{
Data = new Data();
}
[DataMember(Name = "data")]
public Data Data { get; private set; }
}
You could use generics for an abstracted Data
public class Task<T> where T: class , new()
{
public Task
{
Data = new T();
}
[DataMember(Name = "data")]
public T Data { get; private set; }
}
If your service provider is wcf (i guess it is wcf), change the BodyStyle of the method to WebMessageBodyStyle.Bare as mentioned below.
BodyStyle = WebMessageBodyStyle.Bare
it will not wrap the result.

How to post a collection to WebApi using Restangular.Js

This get posted to the server as departments are null
JavaScrtipt code:
var departments = [{ DepartmentName : "Name", DepartmentId : 1}];
Restangular.all('records/StartNewDate').post(departments);
Web Api Controller
public HttpResponseMessage StartNewDate(DepartmentViewModel[] departments)
{
....
....
}
Server Model
public class DepartmentViewModel
{
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
}
You have to JSON.stringify the object before you send it in the payload:
return Restangular.all('records/StartNewDate').post(JSON.stringify(departments));

Serialize JSON in ASP.NET

I am new in ASP.NET world and I am trying to achieve following.
I need to serialize API of this format
{
"results": {
"profile": {
"firstname": "John,
"lastname": "Newman",
},
"credit": {
"amount": 30
}
}
}
The problem is that I don't know how to model my data. I need a results object, which contains 2 other objects (profile and credit). You can see some sample code below.
public class Results
{
public class Data {
public Profile profile { get; set; }
public Credit credit {get; set; }
}
public class Profile {
public String firstname {get; set; }
public String lastname { get; set; }
}
public class Credit {
public int amount { get; set; }
}
}
static void Main(string[] args)
{
Results results= new Results
{
Data = new Data{
Profile = new Profile {
firstname = "John",
lastname = "Newman"
},
Credit = new Credit {
balance = "30"
}
}
};
string json = JsonConvert.SerializeObject(results);
Console.WriteLine(json);
}
The error I get is "Member Data cannot be initialized. It is not a field or property. What am I doing wrong?
Try this instead:
public class Profile
{
public String firstname { get; set; }
public String lastname { get; set; }
}
public class Credit
{
public int amount { get; set; }
}
public class Result
{
public Profile profile { get; set; }
public Credit credit { get; set; }
}
public class Wrapper
{
public Result results { get; set; }
}
static void Main(string[] args)
{
var wrapper = new Wrapper
{
results = new Result
{
profile = new Profile
{
firstname = "John",
lastname = "Newman"
},
credit = new Credit
{
amount = 30
}
}
};
string json = JsonConvert.SerializeObject(wrapper);
Console.WriteLine(json);
}
Try this :
static void Main(string[]args) {
Base results = new Base() {
Results = new Results() {
profile = new Profile() {
firstname = "John",
lastname = "Newman"
},
credit = new Credit() {
amount = 30
}
}
};
string json = JsonConvert.SerializeObject(results);
Console.WriteLine(json);
Console.ReadLine();
}
public class Base {
public Results Results {get;set;}
}
public class Results{
public Profile profile {get;set;}
public Credit credit {get;set;}
}
public class Profile{
public String firstname {get;set;}
public String lastname {get;set;}
}
public class Credit{
public int amount {get;set;}
}
Class Base wraps Results class to get the required JSON structure.

Resources