Answer the question
In order to leave comments, you need to log in
How to hide unwanted fields in JSON response using Dapper?
I am writing a REST API server on ASP.NET Core 2.1. I want to use Dapper as ORM. Previously, he developed only small desktop projects for working with the database.
There is a class corresponding to a table in the database:
public class User
{
public int id { get; set; }
public string FIO { get; set; }
public int age { get; set; }
public string city { get; set; }
public string somedata1 { get; set; }
public string somedata2 { get; set; }
public string somedata3 { get; set; }
}
public interface IUser
{
IEnumerable<User> GetUsers();
IEnumerable<User> GetSomeData1();
IEnumerable<User> GetSomeData2();
}
public class UserRepository : IUser
{
/* ... */
public IEnumerable<User> GetUsers()
{
using (IDbConnection connection = GetConnection())
{
return connection.Query<User>("select id, fio, age, city, somedata1, somedata2, somedata3 from users");
}
}
}
[HttpGet]
public IEnumerable<User> GetUsers()
{
return _userRepository.GetUsers();
}
[{"id":1, "fio":"Иванов И. И.", "age":10, "city":"dc", "somedata1":"data1", "somedata2":"data2", "somedata3":"data3"}]
public IEnumerable<User> GetSomeData1()
{
using (IDbConnection connection = GetConnection())
{
return connection.Query<User>("select id, fio, somedata3 from users where id in (1,2)");
}
}
[{"id":1, "fio":"Иванов И. И.", "somedata3":"data3"},
{"id":2, "fio":"Петров А. А.", "somedata3":null}]
[{"id":1, "fio":"Иванов И. И.", "age":null, "city":null, "somedata1":null, "somedata2":null, "somedata3":"data3"},
{"id":2, "fio":"Петров А. А.", "age":null, "city":null, "somedata1":null, "somedata2":null, "somedata3":null}]
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
on the field of the entity class, but it seems that this method will not work for me, because it will also be necessary to return JSON with Null fields.
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question