Error: The json property name for collides with another property in .Net 6
Hi Guys, I am a developer in .Net and I have a project that needs to maintain and upgrade from .net core 3.1 to .net 6.
After upgrading and building all successed. I run the app but have an exception threw: System.InvalidOperationException: The json property name for "model.BooksModel.BookName" collides with another property.
System.InvalidOperationException: The json property name for "model.BooksModel.BookName" collides with another property.
at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_SerializerPropertyNameConflict(Type type, .....)
at System.Text.Json.Serialization.Metadata.JsonTypeInfo.CacheMember()
at System.Text.Json.Serialization.Metadata.JsonTypeInfo.CacheMember(Type declaringType)
at System.Text.Json.Serialization.Metadata.JsonTypeInfo..ctor(Type type)
at System.Text.Json.JsonSerializerOption.<Initial...>
at System.Text.Json.JsonSerializerOption.GetOrAddClass(Type type)
at System.Text.Json.JsonSerializerOption.GetTypeInfo(Type runtimeType)
Here is my code :
public async Task<IEnumerable<BooksModel>> Books(int storeId)
{
try{
var books = await _context.Books.Where(a => a.StoreId == storeId).ToListAsync();
return contacts;
}
catch(Exception ex){
return null;
}
}
public class BooksModel{
public int Id { get; set; }
public string BookName { get; set; }
public string bookname { get; set; }
public string Author { get; set; }
public float Price { get; set; }
public DateTime PublishDate { get; set; }
}
I don't know why book modes had two bookname
properties. I research on google and added the config below into Startup.cs
, ConfigurationServices()
method:
services.AddControllers().AddJsonOptions(options =>
{ options.JsonSerializerOptions.PropertyNameCaseInsensitive = true; });
Anyone can help me with this.
Thanks in advance
-
P-1
Prekshi Gupta May 21 2022
Please don't enable case sensitive for JSON. You can set it like this:
services.AddControllers().AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNameCaseInsensitive = false; });
And add JsonPropertyName to help define names for duplicate properties, like this:
public class BooksModel{ public int Id { get; set; } [JsonPropertyName("BookName")] public string BookName { get; set; } [JsonPropertyName("bookname")] public string bookname { get; set; } public string Author { get; set; } public float Price { get; set; } public DateTime PublishDate { get; set; } }
And it will solve the issues for you.
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.