ServiceStack.Text and ISODate("") - c#

Why ServiceStack.Text DeserializeFromString cant convert ISODate formats.
For example, i have json string like
{ "Count" : 4, "Type" : 1, "Date" : ISODate("2013-04-12T00:00:00Z") }
and class
public class TestClass
{
public int Count { get; set; }
public int Type { get; set; }
public DateTime Date { get; set; }
}
and when i try to deserialize from string
JsonSerializer.DeserializeFromString<TestClass>(json);
give me output like

ServiceStack.Text understands ISO8601, too.
You can configure it as the default behaviour with:
JsConfig.DateHandler = JsonDateHandler.ISO8601;
See this answer for more information.

JSON expects the date format like this
"LastRequestTime":"\/Date(928129800000+0530)\/"
So change you date value in Json string and then try. it will deserialized that property properly.

Related

JSON Key name with spaces [duplicate]

This question already has answers here:
RestSharp - deserialize json response with invalid key name (contains a period )
(2 answers)
Closed 1 year ago.
{
"odata.metadata": "sometext",
"odata.nextLink": "sometext",
"value": [{
"odata.type": "SP.Data.RegionsListItem",
"odata.id": "07404daa-61b5-4947-af9f-38f29822f775",
"odata.etag": "\"3\"",
"odata.editLink": "Web/Lists(guid'65dc896b-df87-4145-98d9-57c7ea619e66')/Items(3)",
"FileSystemObjectType": 0,
"Id": 3,
"ServerRedirectedEmbedUri": null,
}]
}
this is an example of my Json string i cant change its key names any sugestion? thanks in advance.
Depending on the library you are using for deserialization you can mark model fields with corresponding attributes - for example JsonPropertyNameAttribute for System.Text.Json or JsonPropertyAttribute for Newtonsoft.Json.
Newtonsoft.Json:
public class Root
{
[JsonProperty("odata.metadata")]
public string OdataMetadata { get; set; }
[JsonProperty("odata.nextLink")]
public string OdataNextLink { get; set; }
[JsonProperty("value")]
public List<Value> Value { get; set; } // do the same for Value type
}
var result = JsonConvert.DeserializeObject<Root>(json);
System.Text.Json:
public class Root
{
[JsonPropertyName("odata.metadata")]
public string OdataMetadata { get; set; }
[JsonPropertyName("odata.nextLink")]
public string OdataNextLink { get; set; }
[JsonPropertyName("value")]
public List<Value> Value { get; set; }
}
var result = JsonSerializer.Deserialize<Root>(json);
When you create a class for your data, you can use annotations for the class members. For instance when using Newtonsoft.Json it works this way:
class MyData {
[JsonProperty("odata.metadata")]
public string Metadata {get;set;}
[JsonProperty("odata.nextlink")]
public string NextLink {get;set;}
...
}
With other libraries, the annotations may be named differently. Also make sure, you are importing the correct namespace and use the correct annotations for the library you are using. Ie for instance the System.Text.Json.JsonPropertyName annotation won't have any effect, when deserializing with Newtonsoft.Json and vice versa.
Then you can deserialize
var data = JsonConvert.DeserializeObject<MyData>(thejsonstring);
and access the property with its .NET name
var metadata = data.Metadata;

How to deserialize object with date in C# [duplicate]

This question already has answers here:
Deserializing dates with dd/MM/yyyy format using Json.Net
(9 answers)
Closed 6 years ago.
I have this Json from a web api:
jsonstring ={"users":[{"id":1123,"last_update":"2016-02-28 14:53:04"}],"page":1,"pages":1}
which I want to deserialize in an object like:
public class Rootobject
{
public User[] users { get; set; }
public int page { get; set; }
public int pages { get; set; }
}
public class User
{
public int id { get; set; }
public DateTime last_update { get; set; }
}
for this I use:
var obj= JsonConvert.DeserializeObject<Rootobject>(jsonString);
the result has null for last_update.
jsonstring is a string result from WebClient.DownloadString(url); which look like above example.
How can I get the date on deserialization?
Edit:
None of the solutions from this post Deserializing dates with dd/mm/yyyy format using Json.Net help me fix my issue.
var obj = JsonConvert.DeserializeObject<Rootobject>(jsonString,
new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
Fiddle
Change the property last_update as Nullable, Then it allows you to assign the null literal to the DateTime type. It provides another level of indirection. So use like the following:
public DateTime? last_update { get; set; }
This is for accepting The date even if it is null, you can specify the Date format While Deserializing the JSON. Use this Thread for that
"2016-02-28 14:53:04" is not a valid RFC3339 date time, and I think it can't parse it because of that.
It has to be:
2016-02-28T14:53:04
Also note that the can't be null, since DateTime is a struct. To make it nullable, make the data type DateTime? which does allow null values.

Modify a JSON string

I have a string in JSON format as follows
string jsonStr = "{"Type":1, "Id":1000,"Date":null,"Group": "Admin","Country":"India","Type":1}";
I want to modify this string so that Id attribute should always be the first. The order of attributes matters.
Is there any way I can modify this string.
I tried searching google but did not find appropriate solution.
Any help would be appreciated.
EDIT:
I also tried to deserialize object using
object yourOjbect = new JavaScriptSerializer().DeserializeObject(jsonStr);
But here also the "type" attribute comes first. I dont find any way to move the attributes within this deserialized object
It's possible. Use the JsonProperty attribute, property Order.
http://www.newtonsoft.com/json/help/html/JsonPropertyOrder.htm.
Let me know if it works.
Instead of attempting to manipulate the order of the outputted JSON and comparing strings, I would transform both JSON strings that you want to compare, into objects and then perform your comparison. You could then compare individual properties or entire objects with something like the following:
void CompareJSON()
{
string json = #"{""Type"":1, ""Id"":1000,""Date"":null,""Group"": ""Admin"",""Country"":""India"",""Type"":1}";
string jsonToCompare = "JSON TO COMPARE";
MyObject myJsonObject = JsonConvert.DeserializeObject<MyObject>(json);
MyObject myJsonObjectToCompare = JsonConvert.DeserializeObject<MyObject>(jsonToCompare);
if (myJsonObject.Id == myJsonObjectToCompare.Id)
{
// Do something
}
}
class MyObject
{
public int Id { get; set; }
public int Type { get; set; }
public DateTime? Date { get; set; }
public string Group { get; set; }
public string Country { get; set; }
}
Please note that this example is carried out using the Newtonsoft.JSON library. More information on the library can be found here.
Just make your JSON into a c# class with Id first and then serialize it again if that is what you need. You do know that you have "Type" twice in the JSON string? In this solution it will get "fixed" so you only have it once as it should be. But if your string really is with two Type this wont work since the strings will be incorrect. If they really are like that you need to do some ugly string manipulation to fix the order but i hope the first string is incorrect only here and not in your code.
private void Test() {
string json = #"{""Type"":1, ""Id"":1000,""Date"":null,""Group"": ""Admin"",""Country"":""India"",""Type"":1}";
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
MyJsonObject myJsonObject = jsonSerializer.Deserialize<MyJsonObject>(json);
string s = jsonSerializer.Serialize(myJsonObject);
//Returns: {"Id":1000,"Type":1,"Date":null,"Group":"Admin","Country":"India"}
}
class MyJsonObject {
public int Id { get; set; }
public int Type { get; set; }
public DateTime? Date { get; set; }
public string Group { get; set; }
public string Country { get; set; }
}

How to insert ISODate(DateTime) to mongodb with c#

I have one class.
I adding class to mongodb.
but DateTime Properties as shows the string
c#
public class FRM_FORMREQUEST
{
public int ORACLE_ID { get; set; }
public string FORMNUMBER { get; set; }
public string COMPANYCODE { get; set; }
public DateTime? RECORDDATE { get; set; }
public string RECORDUSER { get; set; }
}
mongodb record
{
"_id" : ObjectId("56927dfc249d951f1031f526"),
"ORACLE_ID" : 771653,
"FORMNUMBER" : "4992014309217",
"COMPANYCODE" : "499",
"RECORDDATE" : "2014-08-21T19:35:27",
"RECORDUSER" : "parttime35"
}
Business
var jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(FRM_FORMREQUEST);
MongoDB.Bson.BsonDocument document = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(jsonData);
frmFormCollection.Insert(document);
I want insert like Date
thanks for all help.
The problem is that you're serializing it to JSON using Json.Net, which will write the dates as strings in the ISO 8601 standard format by default. Then you're de-serializing it to a BsonDocument using the BsonSerializer, which (unless you give it any other instructions) will just assume those are strings.
I have to ask, why jump through these hoops? Why not just let the driver serialize your object for you when you call Insert()?
collection.Insert(FRM_FORMREQUEST);
Or, if you have to work with a BsonDocument, use the mongo BsonSerializer to convert your object directly (instead of converting it to Json first).
var document = FRM_FORMREQUEST.ToBson();
collection.Insert(document);

Deserializing JSON collection in C#

This is a JSON message I get from server (which I can't change). There might be many more objects (time / value) returned, but in this case there is only one. The format stays the same regardless.
{
"data": [
{
"time": "2014-12-12T13:52:43",
"value": 255.0
}
]
}
I'm trying to deserialize the JSON to a very simple C# object.
public class Dataentry {
public float Value { get; set; }
public DateTime Time { get; set; }
}
I've tried deserialization with Newtonsoft's JSON.Net and RestSharp libraries with no success. The following code doesn't work, but neither does anything else I've tried :-) I get no error -- just an empty object with default initial values.
var myObject = JsonConvert.DeserializeObject<Dataentry> (jsonString);
Since those libraries are not very intuitive or well documented in this kind of case, I'm lost. Is this kind of JSON impossible to deserialize? I really would like to use a ready-made library, so any help would be appreciated.
This is not working because your JSON is specifying a collection and you are trying to deseralize into one object. There are plenty of json to c# class generators you can paste json into to get an appropriate class definition(s) one such generator is located here
A more appropriate definition would be
public class Datum
{
public string time { get; set; }
public double value { get; set; }
}
public class RootObject
{
public List<Datum> data { get; set; }
}
Then deseralize as
var myObject = JsonConvert.DeserializeObject<RootObject> (jsonString);
I'd like add some extra explanetion to your question...
You write I'm trying to deserialize the JSON to a very simple C# object. - unfortunatelly this is not the complete truth. What you are trying is to deserialize a collection of a very simple C# objects. The indicator for this are the square brackets in your json:
{
"data": [
{
"time": "2014-12-12T13:52:43",
"value": 255.0
}
]
}
It means that there is a class with a property named data (it can ba mapped to some other name but for the sake of simplicity let's stick to this name) and that this property is a collection type. It can be one of any types that support the IEnumerable interface.
public class DataCollection
{
public DataItem[] data { get; set; }
//public List<DataItem> data { get; set; } // This would also work.
//public HashSet<DataItem> data { get; set; } // This would work too.
}
public class DataItem
{
public float value { get; set; }
public DateTime time { get; set; } // This would work because the time is in an ISO format I believe so json.net can parse it into DateTime.
}
The next step is to tell Json.Net how to deserialize it. Now when you know it's a complex data type you can use the type that describes the json structure for deserialization:
var dataCollection = JsonConvert.DeserializeObject<DataCollection>(jsonString);
If you didn't have the data property in you json string but something like this:
[
{
"time": "2014-12-12T13:52:43",
"value": 255.0
},
{
"time": "2016-12-12T13:52:43",
"value": 25.0
},
]
you could directly deserialize it as a collection:
var dataItems = JsonConvert.DeserializeObject<List<DataItem>>(jsonString);
or
var dataItems = JsonConvert.DeserializeObject<DataItem[]>(jsonString);
change your DateEntry binding Definition
public class ArrayData{
public DataEntry data {set; get;}
}
public class DataEntry {
public float Value { get; set; }
public DateTime Time { get; set; }
}
in your method now you can received an ArraData Object
be careful with datetime string values sent for correct binding

Categories

Resources