i work with .net core 2.2, i tried to deserialize datas from WebApi but TimeSpan Type is not converted.
My InnerException is :{"Could not cast or convert from System.String to System.TimeSpan."}
My ErrorMessage is :{"
Error converting value "PT20H20M" to type 'System.TimeSpan'. Path 'value[0].StartTime', line 1, position 179."}
the problem is on a member of my class:
public TimeSpan StartTime { get; set; }
Can someone get the same error or can someone give me some ideas to how manage the problem.
Thanks !
Well, I guess the error is that the default converter does not know the format that you are trying to send in. You have to use a format that it understands or use a custom converter or use a string and convert it yourself afterwards.
If you run TimeSpan.Parse("PT20H20M") you will get an error that says it's not a valid format.
It seems that this call can get you a TimeSpan:
System.Xml.XmlConvert.ToTimeSpan("P2DT01H")
You can use a custom converter as described here or here (First one is for .net core 3).
Related
I am developing a ASP.NET Core 3.1 website and I have data in a Dictionary<string, object> that I want to Serialize/Deserialize using Microsoft System.Text.Json (I am new to Json serialize/deserialize in fact). The data comes from a PostgreSQL DB query and one of the returned values is a comma-separated list of integers (converted to string) that results from the STRING_AGG function. The image below shows one of the entries of the Dictionary:
I serialize it using the following code. Please note that I have tried both Microsoft System.Text.Json and Newtonsoft.
jsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(result);
//jsonResult = JsonSerializer.Serialize(result);
The data in the Dictionary should be deserialized according to the following class structure:
I use the following code:
//IEnumerable<SeccGralContenidoViewModel> seccGralContenido = JsonSerializer.Deserialize<IEnumerable<SeccGralContenidoViewModel>>(_seccGralContenidoRepository.Read());
IEnumerable<SeccGralContenidoViewModel> seccGralContenido = Newtonsoft.Json.JsonConvert.DeserializeObject <IEnumerable<SeccGralContenidoViewModel>>(_seccGralContenidoRepository.Read());
However, an exception is thrown when deserializing no matter if I use Newtonsoft or System.Text.Json:
I am originally using System.Text.Json namespace but I also tried using Newtonsoft. After analyzing a bit deeper, I see that the problem could be the way in which data is saved to the Dictionary but I have not found a workaround.
If you don't want to write a custom converter then the simplest solution is to introduce another property:
public string CategoriasContenidolds {get; set;}
private static char delimiter = ',';
[JsonIgnore]
public string[] CategoriasContenidolds_Collection
{
get => CategoriasContenidolds.Split(delimiter).Select(item => item.Trim()).ToArray();
set => CategoriasContenidolds = string.Join(delimiter, value);
}
The serializer will use the CategoriasContenidolds property during serialization and deserialization
You should use CategoriasContenidolds_Collection (or name whatever you want) in your business logic
By explicitly marking this property with JsonIgnore the serializer will ignore that
I could solve my issue by directly getting JSON formatted results from queries. PostgreSQL does an excellent job. This way I also avoid performing a 2-step process: first, getting the query result; second, serializing to JSON.
I try to realize database access decorator based on Expression types. So, I've already tried many different json serializing libraries, started from Newtonsoft Json till DataContractJsonSerializator and etc.
1) Most of serializators crash on Expression type serialization (including System.Text.Json.Serialization).
2) Newtonsoft.JsonSerializer successfully serialize Expression<Func<User, bool>> test = e => e.Id == sameUser.Id, where User is the class like:
public class User
{
public Guid Id { get; set; }
public string Fullname { get; set; }
}
and sameUser is an object of User class.
But Newtonsoft.JsonSerializer produces string of ~169-200 millions symbols. I don't know does Newtonsoft.JsonSerializer correctly deserialize this json of the other side becauseof the size. Ofcourse, I've tried to use different serializing options.
3) ServiceStack.Text.JsonSerializer successfully serialize Expression<Func<User, bool>> test = e => e.Id == sameUser.Id with normal json size (approx 2-3 thousands symbols), but on the deserialization Expression.Body always null after deserialization (and this really strange - serialized json has it well-serialized).
4) Serialize.Linq successfully passed the test.
I want to understand, what the reason of this strange behavior of main serializers like Newtonsoft, ServiceStack, Microsoft, etc?
P.S. I'ven't tested protobuf-net and MessagePack yet, I'll do this soon,but think they have the same troubles with Expression class object serialization/deserialization.
Expression has cyclical dependencies an non serializable references that is not suitable for serialization. If you want to serialize the debug string representation of an Expression do that in your code and serialize the string, don’t expect serialization libraries to attempt to serialize a non-serializable class that’s impossible to deserialize.
If you want to serialize code, send raw source code and use Roslyn or Code DOM to execute the source code received, you’ll need to validate any untrusted user code for potential security vulnerabilities or unwanted behavior before evaluating it.
I need to deserialize this, which is encoded in JSON and I can not, I need it, anyone can help me?
[{"idReservation":2560,
"startDate":"30/09/2013 09:00",
"endDate":"30/09/2013 09:10",
"timeOut":"24/09/2013 16:02:23",
"idResource":1477,
"resourceDescription":"Profesional",
"players":
[{"idPlayer":283,
"idCustomer":2,
"name":"Ignacio",
"image":"/public/images/interface/customer/user.png",
"total":0}],
"anulable":true,
"name":"Ignacio",
"price":0,
"status":"Reservada",
"parententityname":"",
"idparententity":"",
"unixTime":1380524400},]
greetings and thank you very much
As #YuriyGalanter suggests Json.NET will do the job, it has great performance and avoids the problem you get when trying to serialise a javascript datetime object to .net datetime object.
The documentation provides an example of how to deserialise an object.
Expanding on Mr Shoubs' answer:
1) Download the Json.Net DLL per Mr Shoubs' answer.
2) Add a reference to this DLL in your Visual Studio Project.
3) Create a VB Reservation class that you want to end up with:
Public Class Reservation
Public Property idReservation() as Integer
Public Property startDate() as Date
...
End Class
Make the spelling and casing exactly as they are in the JSON object to keep things simple.
4) Declare an object of type Reservation and populate it with the JSON string you have - using the DeserializeObject method:
Dim obj As Reservation
obj = JsonConvert.DeserializeObject(Of Reservation)(yourJsonString)
obj should now contain the data you want.
I'm working on a Windows 8 Metro application that references a c# WinRT project. Among other things, the c# project makes web requests to an Azure service to perform CRUD operations against a SQL Azure database.
When performing a POST operation on the service, I'm serializing an instance of a class and putting it in the body of the request.
public sealed class Foo
{
int FooId { get; set; }
DateTimeOffset FooDate { get; set; }
}
When this is serialized using the DataContractJSONSerializer, the result is something like this:
{"FooId":1,"FooDate":{"DateTime":"/Date(1342732970000)/","OffsetMinutes":-420}}
FYI that this is 7/19/2012 2:22:50PM -07:00.
OK great ... Only problem is that the Azure service is expecting just a DateTime, not a DateTimeOffset. I don't own the Azure service so I can't change its behavior.
So (ignoring that I'm losing the offset) what I need is this to serialize into:
{"FooId":1,"FooDate":"/Date(1342732970)/"}
My first approach was to add a new aliased DateTime property/datamember to the class with a getter that returns the DateTime portion of the DateTimeOffset. However, WinRT doesn't support the DateTime type.
There are a couple of hacky ways to get around this, but I wanted to see if there's an elegant way to do this before resorting to one of these:
Regex on the serialization result before the POST
String property on the class that returns a JSON formatted date
Thanks
I ended up implementing a property on the class with a getter that formats the date appropriately.
I decorated the Foo field with the IgnoreDataMember attribute so that it gets ignored during serialization. I then added a new field and gave it the alias of Foo for serialization.
Thanks
I'm facing following error while trying unmarshal java.util.Date from JSON in grails controller.
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '2011-10-07 10:24:40' with class 'java.lang.String' to class 'java.util.Date'**
Also, I've tried the following method but still no luck, actually I've doubt wether I've implemented following in right way or not because when i put println statements in following method:
public CustomDateBinder(List formats)
Nothing prints on console.
Grails Date unmarshalling
According to the description of your error message you are trying to convert a String to Date, if you want to do it manually you can use the following method in your Controller (since Grails 2)
def val = params.date('myDate', 'dd-MM-yyyy') //Obviously you need to change the format
Check the following post for more info: http://mrhaki.blogspot.com/2012/01/grails-goodness-date-request-parameter.html