I'm trying to store a model to the redis that has 3 string fields, each one is serialized JSON
I have no problem in setting it and I can see it in redis insight
but when getting it from redis it fires error JSON exception when digging deep into it, the problem with those string fields that contains JSON
[Document(Prefixes = new[] { "Demo" })]
public class Demo
{
[Indexed]
public string ReferenceNumber { get; set; }
[Indexed]
public string Note { get; set; }
[Indexed]
public string ItemsData { set; get; } <-- those the string fields that contains json
[Indexed]
public string SkillsData { get; set; }
[Indexed]
public string Data { get; set; }
}
I'm using redis OM with Dot Net Core 6.
Furthermore, I tried to change the document type from hash to JSON and nothing happened
I didn't find a way to do so in HashSet so I decided to change the type of the document to Json and I got to retrieve the data without any problem
I am trying to implement the Syncfusion Blazor QueryBuilder component to build dynamic search filters.
I can successfully store query builder rules to my DB after mapping to my C# class model.
But when I try to re-map these rules back to the Syncfusion "RuleModel" class I get error below in the browser.
It appears to be caused by the dynamic property types on the "Operate" and "Value" fields.
When I get the error, these properties have the "ValueKind" element. When this is not present, it works fine (eg. If I manually create a new RuleModel())
Error in Browser, when QueryBuilderObj.SetRules() method is called..
Error: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot implicitly convert type 'System.Text.Json.JsonElement' to 'string'
at CallSite.Target(Closure , CallSite , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
at Syncfusion.Blazor.QueryBuilder.Internal.QueryBuilderRules`1.SetField()
at Syncfusion.Blazor.QueryBuilder.Internal.QueryBuilderRules`1.OnParametersSetAsync()
at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
Client Code
<SfQueryBuilder TValue="#FilterColumns" #ref="QueryBuilderObj" MaxGroupCount=3>
<QueryBuilderColumns>
<QueryBuilderColumn Field="Status" Label="Status" Type="ColumnType.String"></QueryBuilderColumn>
<QueryBuilderColumn Field="DepartmentCode" Label="DepartmentCode" Type="ColumnType.String"></QueryBuilderColumn>
</QueryBuilderColumns>
</SfQueryBuilder>
<button type="button" #onclick="getRules">Get Rules</button>
#code {
SfQueryBuilder<FilterColumns> QueryBuilderObj;
public class FilterColumns
{
public string Status { get; set; }
public string DepartmentCode { get; set; }
}
[Parameter]
public RuleModel rules { get; set; }
private void getRules()
{
QueryBuilderObj.SetRules(rules.Rules, rules.Condition);
}
}
Syncfusion RuleModel Class
public class RuleModel
{
public RuleModel();
public string Condition { get; set; }
public string Field { get; set; }
public string Label { get; set; }
public bool? Not { get; set; }
public dynamic Operator { get; set; }
public string Type { get; set; }
public dynamic Value { get; set; }
public List<RuleModel> Rules { get; set; }
}
I have replicated the syncfusion RuleModel class exactly as above in my domain model.
Has anyone successfully stored and retrieved QueryBuilder rules from Blazor UI into a C# model/class?
Thanks.
I figured out this problem is due to System.Text.Json behaviour causing the newly created property to have a ValueKind object on each property.
Basically this problem... How do I get System.Text.Json to deserialize objects into their original type?
When I switch to using NewtonSoft JSON.NET to de-serialize the RuleModel, it solved the issue.
Not sure how to make it work with System.Text.Json - but will use Json.Net for now.
I have an MVC Model that generates JSON files, based off of user inputs, that are used as part of an automated workflow. The issue that I am having is figuring out how to change the order in which a list of objects are serialized based off of a specific property value.
Here is a simplified look at my model:
public class Ticket
{
public string TicketNumber { get; set; }
public string TicketName { get; set; }
public string ApplicationName { get; set; }
public IList<Jams> JamsList { get; set; }
}
public class RootObject
{
public Ticket ChangeTicket { get; set; }
}
public class JamsDestination
{
public string Dev { get; set; }
public string QA { get; set; }
public string Prod { get; set; }
}
public class Jams
{
public string TFSLocation { get; set; }
public string FileName { get; set; }
public string JamsType { get; set; }
public JamsDestination JamsLocation { get; set; }
}
(I am using Newtonsoft.Json and the SerializeObject() function in the post section of my controller)
JamsType is a drop down list populated from a sql table (Variable, Job, Trigger, and Box). What I am trying to do is ensure that any Jams change (in the list: JamsList) is serialized in an order that ensures that all Jams changes of JamsType = Box are serialized last, in order to ensure that it will run properly as a part of our automated workflow. Is there any way to accomplish this without setting up some form of Javascript function in the view to reorder them before they are indexed? (My view is a dynamic table setup so it is not guaranteed that there even will be any Jams changes each time, let alone how many are associated with a ticket).
I realized that I just needed to add Linq logic into my controller PRIOR to serializing the JSON file by doing the following:
ticket.JamsList = ticket.JamsList.OrderBy(jams => jams.JamsType == "Box").ToList();
All this actually does is just reorder the list of Jams changes to meet my conditions before it gets serialized, rather than changing the order it serializes the list (how I thought it needed to be performed).
I'm trying to build simple API for training, in my database I got users (firstname, lastname, email password, list<sports>) and sports ( name, userID).
All is okay when I want to get my users, I got an object populated with sports. But the JSON response is incomplete, it is "cut" in the middle.
[{"firstName":"Nicolas","lastName":"Bouhours","email":"n.bouh#test.com","password":"nico#hotmail.fr","sports":[{"name":"Trail","userId":1
This is my controller :
// GET: api/Users
[HttpGet]
public IEnumerable<User> GetUsers()
{
var users = _context.Users.Include(u => u.Sports).ToList();
return users;
}
And my models :
public class Sport : BaseEntity
{
public string Name { get; set; }
public int UserId { get; set; }
public User User { get; set; }
}
public class User : BaseEntity
{
public String FirstName { get; set; }
public String LastName { get; set; }
public String Email { get; set; }
public String Password { get; set; }
public List<Sport> Sports { get; set; }
}
public class SportAppContext : DbContext
{
public SportAppContext(DbContextOptions<SportAppContext> options) : base(options)
{ }
public DbSet<User> Users { get; set; }
public DbSet<Sport> Sports { get; set; }
}
I really don't understand what happen, if you have any idea
I'm running into the same issue right now. You can also change the JSON serialization/configuration settings to ignore self-reference loops, as shown in the accepted answer for this question
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddJsonOptions(options => {
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
}
I had this problem to in one of my projects. This is caused by a self referencing loop.
You need to create some sort of DTO (Data Transfer Object) which will be used to generate your JSON.
In your DTO you remove the inverse relationship so you end up having something like
public class SportDto
{
public string Name { get; set; }
}
public class UserDto
{
public String FirstName { get; set; }
public String LastName { get; set; }
public String Email { get; set; }
public String Password { get; set; }
public List<SportDto> Sports { get; set; }
}
You then map your user User and Sport models to your UserDto and SportDto
A good tool for doing this mapping is AutoMapper. You can read the docs to see how to get started.
After the mapping is done, you Send the DTOs as your JSON and not your models.
Just to add another yet unique scenario where this can occur. This can also happen if your DAL is returning queryables. In my scenario, I was returning a boxed object from the DAL and had something like this as a linq query
...
RootLevelProp1 = "asd",
RootLevelProp2 = "asd",
Trades = b.Trades.OrderBy(c => c.Time).Select(c => new
{
c.Direction,
c.Price,
c.ShareCount,
c.Time
}) //<---- This was being returned as a queryable to the controller
The Trades query was never being executed even though it's root object had .ToListAsync() called on it. What was happening was that the controller would return the result but only up to the Trades section and the Json would not be terminated properly. I then realized an exception was being caught in some custom middleware I wrote in which it was complaining about the data reader already being open. Without going to deep into my investigation, I assumed it had to do something with the DI and how it was handling the lifecycle of the context. The fix was to just add ToList on the trades. It's an ugly way to pass data from the DAL but this is just a fun project.
In my case this solve my issue on core 3, by using Newtonsoft:
https://learn.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-3.0#add-newtonsoftjson-based-json-format-support
Prior to ASP.NET Core 3.0, the default used JSON formatters
implemented using the Newtonsoft.Json package. In ASP.NET Core 3.0 or
later, the default JSON formatters are based on System.Text.Json.
Support for Newtonsoft.Json based formatters and features is available
by installing the Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet
package and configuring it in Startup.ConfigureServices.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddNewtonsoftJson();
}
The selected answer was correct in my case as well, my JSON response was getting truncated by a reference loop in my JSON response, and setting ReferenceLoopHandling.Ignore did indeed solve my issue. However, this is not the best solution in my opinion, as this maintains the circular references in your model. A better solution would use the [JsonIgnore] attribute within the model.
The issue in your model is here:
public class Sport : BaseEntity
{
public string Name { get; set; }
public int UserId { get; set; }
public User User { get; set; } //This is the cause of your circular reference
}
public class User : BaseEntity
{
public String FirstName { get; set; }
public String LastName { get; set; }
public String Email { get; set; }
public String Password { get; set; }
public List<Sport> Sports { get; set; }
}
As you can see, your User navigation property is where this response is truncated. Specifically, it will cause each Sport in the json response to contain all of the user information for each sport entry in the response. Newtonsoft does not like this. The solution is to simply [JsonIngore] the navigation properties that cause this circular reference. In your code this would be:
public class Sport : BaseEntity
{
public string Name { get; set; }
public int UserId { get; set; }
[JsonIgnore]
public User User { get; set; } //fixed
}
public class User : BaseEntity
{
public String FirstName { get; set; }
public String LastName { get; set; }
public String Email { get; set; }
public String Password { get; set; }
public List<Sport> Sports { get; set; }
}
Faced similar issue, response was getting truncated. Issue was a getter method which trying to formatting date.
I'm porting a project from Android to Windows Phone 8 and can't find any info on how to specify which JSON key maps to which object field.
The Android code uses Google GSON and the SerializedName annotation to map em in the JSON to the email field in the object.
I'm also controlling which fields are [de]serialized using the Expose annotation. How would I go about doing these same things in my Windows Phone 8 project?
I'd absolutely hate to use a class that looks like this:
public sealed class SomeData
{
public string em { get; set; }
public string un { get; set; }
public string fn { get; set; }
public int tz { get; set; }
}
Thanks.
You can mark properties with DataMember attribute to explicitly specify desired name.
[DataMember(Name = "em")]
public string Email { get; set; }