Linq JSON filter - json

I have a entity A
public class A
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
Now Description property contains JSON serialized DATA like :
{"Year":"2017","Quarter":"2"}
I'd like to know if there is a way to filter on serialized data ?
Let's say I want all A where Description has value 2017 for Year, does linq permit such request ?
Now, Description does not always contains value as JSON. Is there a way to check if Description value is JSON ?
So the final code could look like
DbContext.Set<A>().Where(a => a.Description.Contains("JSON_REGEX") && a.Description.JsonFilter(d => d.Year == 2017));
When I record such DATA I use Newtonsoft.JSON.
EF 6.1.1

Related

is it possible to rename the variable receiving via { get; set; } in c# class?

so I have this class:
public class CheckTweetSingle
{
public int item1 { get; set; }
public int item2 { get; set; }
}
I get a json string that I am converting the values into item1 and item2.
is it possible to change the name of item1 to chairs and item2 to tables, so I can access them via checkTweet.chair instead of checkTweet.item2?
I cannot change the way the json string is coming..
thank you.
You just need to decorate your class properties with the JsonProperty attribute like this
public class CheckTweetSingle
{
[JsonProperty("item1")]
public int chairs { get; set; }
[JsonProperty("item2")]
public int tables { get; set; }
}
This attribute tells to your json library that when deserializing json data the entry with the name "item1" should be assigned to the property chairs. Viceversa if you ever need to serialize that class the value of the property chairs goes to the "item1" entry in the json output
Note: I assume you are using Newtonsoft Json.NET as your json library

ServiceStack ORMLite not deserializing JSON stored in DB text field

I have some telemetry data that was stored in a text field as JSON. I'm attempting to reverse-engineer POCOs to seamlessly extract and present that data without having to do any post-processing ForEach loops.
When I attempt to manually parse the JSON string in the data field, it works. When I am selecting via ORMLite, it comes back with the default object. What am I missing?
Works
string x = "{\"alive\":true,\"paperStatus\":\"0:NoIssue\"}";
var telemetry = JsonSerializer.DeserializeFromString<KioskTelemetryData>(x);
Doesn't populate Data field
var exp = Db.From<KioskTelemetryLog>()
.Where(q => q.Identifier == request.Identifier)
.OrderByDescending(q => q.Timestamp);
var data = Db.Select(exp);
Here is what the data records look like:
Id Identifier IsCurrent RedemptionCenterId Timestamp Status Data
1 XXX 0 NULL 2015-11-24 11:10:53.527 1 {"alive":true,"paperStatus":"1:LowPaper"}
2 XXX 0 NULL 2015-12-01 12:16:56.653 0 {"alive":true,"paperStatus":"0:NoIssue"}
1 XXX 1 NULL 2015-12-01 18:32:11.337 2 {"alive":false}
And here are the POCOs:
[Alias("TelemetryLog")]
public class KioskTelemetryLog
{
public long Id { get; set; }
public string Identifier { get; set; }
public bool IsCurrent { get; set; }
public int? RedemptionCenterId { get; set; }
public DateTime Timestamp { get; set; }
// 0 = okay, 1 = warning, 2 = error
public sbyte Status { get; set; }
public KioskTelemetryData Data { get; set; }
}
public class KioskTelemetryData
{
public bool Alive { get; set; }
public string PaperStatus { get; set; }
}
The default complex type serializer for OrmLite is the JSV Format (except for PostgreSQL which uses JSON). OrmLite does support pluggable text serializers, e.g. you can change SQL Server to use JSON for serializing complex types with:
SqlServerDialect.Provider.StringSerializer = new JsonStringSerializer();
If it's not serializing correctly it's like a serialization error, you can try enable logging for more info about the error, e.g:
LogManager.LogFactory = new ConsoleLogFactory(debugEnabled:true);

Entity not passed on UpdateAsync

Currently I can insert and lookup entities perfectly fine, however when I do
await myTable.UpdateAsync(entity);
It correctly goes into the corresponding TableController but no entities are passed through, every field is null, or its MinValue.
I can put the same entity into an
await myTable.InsertAsync(entity);
and all variables correctly come through at the other end.
Just to add some more information, I am getting the entity originally by
Entity entity = await myTable.LookupAsync(id);
Then I update values on this entity and pass it to the UpdateAsync
The Entity definition on my mobile app is
public Guid Id { get; set; }
public String firstName { get; set; }
public String lastName { get; set; }
public DateTime added { get; set; }
[Microsoft.WindowsAzure.MobileServices.Version]
public string Version { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset? UpdatedAt { get; set; }
public bool Deleted { get; set; }
The entity definition is the same at the TableController, the only difference is that I don't specify the CreatedAt, UpdatedAt, Deleted and Version as they are part of EntityData that I am inheriting from.
At the TableController end here is some more information on the patch.
patch.GetUnchangedPropertyNames().ToList();
Count = 5
[0]: "added"
[1]: "firstName"
[2]: "lastName"
[3]: "Version"
[4]: "CreatedAt"
patch.GetChangedPropertyNames().ToList();
Count = 3
[0]: "Id"
[1]: "UpdatedAt"
[2]: "Deleted"
I also tried changing the Id to a string and removing the DateTime at both ends yet the firstName and lastName never come through.
Due to more debugging (as per my comments below) I correct my statement and say that it is at the TableController end. It is not accepting anything other than Booleans.
The dynamic view will show DateTime or Int32 but no String. For example I added an integer property to my entity and sent this through
{
"Deleted":"false",
"test":123,
"firstName":"test"
}
But here is what I get in the controller.
Just a note, I can change Deleted to true and it reflects correctly.

JSON array is converting to a generic list, but not converting to a generic collection. Why?

I am sending a Json Array from the client web application to asp.net webapi.
For example,
{
"SurveyId":3423,
"CreatorId":4235,
"GlobalAppId":34,
"AssociateList":[
{"AssociateId":4234},
{"AssociateId":43},
{"AssociateId":23423},
{"AssociateId":432}
],
"IsModelDirty":false,
"SaveMode":null
}
Here Associate List is a JSON Array,
Usually it will automatically serialize to a List<> object.
Using the below code ,i am posting the response to the WebApi
public IEnumerable<Associate> Post(ResponseStatus responseStatus)
{
return this.responsestatusrepository.ResponseStatusCheck(responseStatus);
}
The ResponseStatus class is shown below.
public class ResponseStatus : AppBaseModel
{
public int SurveyId { get; set; }
public int CreatorId { get; set; }
public int GlobalAppId { get; set; }
public List<Associate> AssociateList { get; set; }
}
I have changed the List<> to Collection<> as a part of my code analysis correction.
ie, public Collection<Associate> AssociateList { get; set; }
But it is always getting a null value when we are using collection instead of List. Is there any specific reason for this?
Ok, I think I will have to answer this in an indirect way.
What you are passing on to the server is an array of objects (in JSON format), but once you start processing this in C# the array of objects is now treated as a single c# object. Inside this object, your model expects one of the fields to be a Collection of Associate.
Right, when I work with JSON data similar to whats mentioned in this case - I prefer to use Newtonsofts' JOject.
So here is how I made the C# object with the JSON data you provided:
Used your model:
public class ResponseStatus
{
public int SurveyId { get; set; }
public int CreatorId { get; set; }
public int GlobalAppId { get; set; }
public Collection<Associate> AssociateList { get; set; }
}
public class Associate
{
public int AssociateId { get; set; }
}
Made a routine which takes string (the JSON data), and returns an object of type ResponseStatus:
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
---------------------------------------------------------------------
public static ResponseStatus GetResponseStatusObject(string jsonData)
{
JObject jObject = JObject.Parse(jsonData);
return jObject.ToObject<ResponseStatus>();
}
Now when I call this method and pass on the exact same JSON data which you provided, I get this:
This might not directly solve your problem, but hopefully guide you in the right direction in understanding array/object serialization when working with JavaScript/C#.
Best of luck!

deserialize object that contains list of int as property

I'm trying to Deserialize a Json into my object using Newtonsoft.Json.JsonConvert.
My json is:{"SelectedContentsID[]":"31807,32493,39517","pageSize":"20","SisconContentSubDialogEnum":"0","searchCriteria":"","pageIndex":"1"}
and the respective class is:
[DataContract]
public class ContentGetHandlerDTO : ListBaseHandlerDto
{
[DataMember(Name = "SelectedCourseId")]
public int SelectedCourseId { get; set; }
[DataMember]
public System.Collections.Generic.List<int> SelectedContentsID { get; set; }
public ContentGetHandlerDTO() {
this.SelectedContentsID = new System.Collections.Generic.List<int>();
}
}
the ListBaseHandlerDto is just a class that contains some commons properties.
The problem is, the deserializer method is just ignoring the list of int and bringing a null list.
Your Json looks incorrect, it should look like this:
{
"SelectedContentsID":[31807,32493,39517],
"pageSize":"20",
"SisconContentSubDialogEnum":"0",
"searchCriteria":"",
"pageIndex":"1"
}
specifically look at your SelectedContentsID,
you had:
"SelectedContentsID[]":"31807,32493,39517"
when a json int array should look like this:
"SelectedContentsID":[31807,32493,39517]
here is a pretty good reference if you ever get confused - http://www.w3schools.com/json/json_syntax.asp