I am using Newtonsoft.Json in my project for json parsing from server.
public class MyObj
{
public DateTimeOffset TimeStamp { get; set; }
//other fields....
}
Then:
MyObj test = JsonConvert.DeserializeObject<MyObj>(jObject.ToString());
Test:
"TimeStamp": "2018-05-26T04:59:40:888Z" //Could not convert string to DateTimeOffset
"TimeStamp": "2018-05-26T04:59:40:88Z" //Could not convert string to DateTimeOffset
"TimeStamp": "2018-05-26T14:59:40:888Z" //Could not convert string to DateTimeOffset
"TimeStamp": "2018-05-26T14:59:40:88Z" //Could not convert string to DateTimeOffset
"TimeStamp": "2018-05-26T03:29:46.777Z" //works
"TimeStamp": "2018-05-26T13:29:46.77Z" //works
"TimeStamp": "2018-05-26T03:29:46.777Z" //works
"TimeStamp": "2018-05-26T13:29:46.77Z" //works
Error:
Newtonsoft.Json.JsonReaderException: Could not convert string to DateTimeOffset: 2018-05-27T04:59:40:887Z.
I am not sure why this happens, because the date is from server.
Edit:
{
"clientTimestamp": "2018-05-27T06:08:40:688Z",
"modifiedType": "",
"type": "TEXT",
"messageSize": 5,
"roomId": "689355a0-604b-11e8-ae6a-9d170520ec46",
"messageContent": "hello"
}
Update I finally found the issue. It was not the server response that I was parsing. It was my own object that I parsed. The description:
public class TempClass
{
public DateTime TimeStamp { get; set; }
}
Does not work
JObject jObject = new JObject();
jObject.Add("TimeStamp", DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss:fffZ"));
TempClass chatMessage = JsonConvert.DeserializeObject<TempClass>(jObject.ToString());
Works
JObject jObject = new JObject();
jObject.Add("TimeStamp", DateTime.Now);
TempClass chatMessage = JsonConvert.DeserializeObject<TempClass>(jObject.ToString());
Your timestamp is incorrect
Instead of 2018-05-27T06:08:40:688Z should be 2018-05-27T06:08:40.688Z
(the millisecond is separated by a dot . )
Try this
public class RootObject
{
public DateTime clientTimestamp { get; set; }
public string modifiedType { get; set; }
public string type { get; set; }
public long messageSize { get; set; }
public Guid roomId { get; set; }
public string messageContent { get; set; }
}
Then:
MyObj test = JsonConvert.DeserializeObject<RootObject>(jObject.ToString());
In fact
2018-05-27T06:08:40:688Z
Could not convert string to DateTime: 2018-05-27T06:08:40.688Z
2018-05-27T06:08:40.688Z
OK
It seems that this is happening because data from your server is not sent in the correct json format for the Date/Time, and you are trying to deserialize them.
Related
Having json string containing date field
{
"totalSize": 2,
"records": [
{
"Id": "5006C000008ZhEDQA0",
"CreatedDate": "2021-12-01T15:14:20.000+0000",
"CaseNumber": "01378682",
"Status": "Open"
},
{
"Id": "5006C000008ZhE00A0",
"CreatedDate": "2021-12-05T08:00:00.000+0000",
"CaseNumber": "01378692",
"Status": "Open"
}
]
}
I'm trying to do normal Deserialization where CreatedDate datatype is DateTime.
JsonSerializer.Deserialize<SFHistoryResponse>(stringResponse);
I'm getting
The JSON value could not be converted to System.DateTime. Path:
$.records[0].CreatedDate
is there any way to format JSON's date part before Deserialization
The Newtonsoft JSON library can deserialize the string properly without throwing an exception:
using Newtonsoft.Json;
var response = JsonConvert.DeserializeObject<SFHistoryResponse>(stringResponse);
In your case your classes need to be:
public class Record
{
public string Id { get; set; }
public DateTime CreatedDate { get; set; }
public string CaseNumber { get; set; }
public string Status { get; set; }
}
public class SFHistoryResponse
{
public int totalSize { get; set; }
public List<Record> records { get; set; }
}
and when you try to deserialize the json
SFHistoryResponse l = JsonConvert.DeserializeObject<SFHistoryResponse>(jsonString);
tested my self
tbResult.Text = "l.records[0].CreatedDate.ToString() - " + l.records[0].CreatedDate.ToString();
We are running .NET Core 2.1 on Linux. We do a POST with body below, and it seems for all 3 cases the datetime is converted to UTC time, instead of keeping the local time with offset as submitted. What is surprising is that even JSON properties deserialized to string are still showing converted value.
We are trying to retain the local value for further processing.
JSON:
{
"ts": "2020-09-27T01:23:27.047-04:00",
"tsTest": "2020-09-27T01:23:27.047-04:00",
"tsTest2": "2020-09-27T01:23:27.047-04:00"
}
Model:
public class HealthAssessmentResponseDto
{
[JsonProperty("ts")]
// public string LocalDttmStr { get; set; }
public DateTimeOffset LocalDttm { get; set; }
[JsonProperty("tsTest")]
public string LocalDttmStr { get; set; }
[JsonProperty("tsTest2")]
[JsonConverter(typeof(DateFormatConverter), "yyyy-MM-ddTHH:mm:ssK")]
public DateTimeOffset LocalDttmConverted { get; set; }
}
public class DateFormatConverter : Newtonsoft.Json.Converters.IsoDateTimeConverter
{
public DateFormatConverter(string format)
{
DateTimeFormat = format;
}
}
Result
{
"tranId": "7be8989c-c310-4b7a-a5a2-1706398f94f8",
"payload": {
"rto": true,
"message": "LocalDttmStr: 2020-09-27T05:23:27, LocalDttmConverted: 09/27/2020 05:23:27 +00:00, DatetimeOffset: 09/27/2020 05:23:27 +00:00"
}
}
I am new to Json and trying to do some examples with it. I have Json data like this:
{
"Title": "The Avengers",
"Year": "2012",
"Rated": "PG-13",
"Released": "04 May 2012",
"Runtime": "143 min",
"Genre": "Action, Adventure, Sci-Fi",
"Director": "Joss Whedon",
"Writer": "Joss Whedon (screenplay), Zak Penn (story), Joss Whedon (story)",
"Actors": "Robert Downey Jr., Chris Evans, Mark Ruffalo, Chris Hemsworth",
"Plot": "Earth's mightiest heroes must come together and learn to fight as a team if they are going to stop the mischievous Loki and his alien army from enslaving humanity.",
"Language": "English, Russian, Hindi",
"Country": "USA",
"Awards": "Nominated for 1 Oscar. Another 38 wins & 79 nominations.",
"Poster": "https://m.media-amazon.com/images/M/MV5BNDYxNjQyMjAtNTdiOS00NGYwLWFmNTAtNThmYjU5ZGI2YTI1XkEyXkFqcGdeQXVyMTMxODk2OTU#._V1_SX300.jpg",
"Ratings": [
{
"Source": "Internet Movie Database",
"Value": "8.0/10"
},
{
"Source": "Rotten Tomatoes",
"Value": "92%"
},
{
"Source": "Metacritic",
"Value": "69/100"
}
],
"Metascore": "69",
"imdbRating": "8.0",
"imdbVotes": "1,200,683",
"imdbID": "tt0848228",
"Type": "movie",
"DVD": "25 Sep 2012",
"BoxOffice": "$623,279,547",
"Production": "Walt Disney Pictures",
"Website": "http://marvel.com/avengers_movie",
"Response": "True"
}
I can get the data and read it just fine but when it comes deserialize I get the following error:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Deneme.Modeller.Main]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
This is my code
string url = "http://www.omdbapi.com/?apikey=7663ce8e&t=Avengers";
WebRequest request = WebRequest.Create(url);
WebResponse reply;
reply = request.GetResponse();
StreamReader returninfo = new StreamReader(reply.GetResponseStream());
string getinfo = returninfo.ReadToEnd();
List<Main> Info = JsonConvert.DeserializeObject<List<Main>>(getinfo);
and for models this is first main:
public string Title { get; set; }
public string Year { get; set; }
public string Rated { get; set; }
public string Released { get; set; }
public string Runtime { get; set; }
public string Genre { get; set; }
public string Director { get; set; }
public string Writer { get; set; }
public string Actors { get; set; }
public string Plot { get; set; }
public string Language { get; set; }
public string Country { get; set; }
public string Awards { get; set; }
public string Poster { get; set; }
public List<Rating> Ratings { get; set; }
public string Metascore { get; set; }
public string imdbRating { get; set; }
public string imdbVotes { get; set; }
public string imdbID { get; set; }
public string Type { get; set; }
public string DVD { get; set; }
public string BoxOffice { get; set; }
public string Production { get; set; }
public string Website { get; set; }
public string Response { get; set; }
second one is for Ratings:
public string Source { get; set; }
public string Value { get; set; }
public virtual ICollection<Main> Mains { get; set; }
It's about Json array, but I looked asked questions about this problem and tried to fix it but no luck. What am I missing?
You are trying to deserialize a single object of type Main into a list of objects.
You can either change your code to deserialize into a single object instead of a list or you can alter your JSON to represent an array of objects.
The first option would be
Main Info = JsonConvert.DeserializeObject<Main>(getinfo);
And the second option
[{"Title":"The Avengers","Year":"2012","Rated":"PG-13","Released":"04 May 2012","Runtime":"143 min","Genre":"Action, Adventure, Sci-Fi","Director":"Joss Whedon","Writer":"Joss Whedon (screenplay), Zak Penn (story), Joss Whedon (story)","Actors":"Robert Downey Jr., Chris Evans, Mark Ruffalo, Chris Hemsworth","Plot":"Earth's mightiest heroes must come together and learn to fight as a team if they are going to stop the mischievous Loki and his alien army from enslaving humanity.","Language":"English, Russian, Hindi","Country":"USA","Awards":"Nominated for 1 Oscar. Another 38 wins & 79 nominations.","Poster":"https://m.media-amazon.com/images/M/MV5BNDYxNjQyMjAtNTdiOS00NGYwLWFmNTAtNThmYjU5ZGI2YTI1XkEyXkFqcGdeQXVyMTMxODk2OTU#._V1_SX300.jpg","Ratings":[{"Source":"Internet Movie Database","Value":"8.0/10"},{"Source":"Rotten Tomatoes","Value":"92%"},{"Source":"Metacritic","Value":"69/100"}],"Metascore":"69","imdbRating":"8.0","imdbVotes":"1,200,683","imdbID":"tt0848228","Type":"movie","DVD":"25 Sep 2012","BoxOffice":"$623,279,547","Production":"Walt Disney Pictures","Website":"http://marvel.com/avengers_movie","Response":"True"}]
(simply add brackets)
Which option you have to choose is depending on your requirements, i.e. if you want to allow multiple objects or just one.
Main Info = JsonConvert.DeserializeObject<Main>(getinfo);
Your json string has only one Main object, you were trying to get a List
You try to deserialize one JSON object into a list of objects.
This is an example of simple object:
{ "field": 123 }
To deserialize it you need to:
var obj = JsonConvert.DeserializeObject<SomeModel>(json);
But if you have an array of objects:
[{ "field": 123 }, { "field": 123 }]
You will be able to deserialize them to a list like this:
var objs = JsonConvert.DeserializeObject<SomeModel[]>(json);
or
var objs = JsonConvert.DeserializeObject<List<SomeModel>>(json);
Solutions to your question:
Change deserialization type to a single object.
Wrap your JSON around with []
when we call api 'http://www.omdbapi.com/?apikey=7663ce8e&t=Avenger' we gets an objet not an array of object
try
var info = JsonConvert.DeserializeObject<Main>(getinfo);
If you want list of movies try a other api b.e.: themoviedbAPI
I have a JSON file that has been serialized through an API, in which I need to deserialize it to use the data it generated in my code. The issue is that I'm getting an Exception Unhandled error in which I have tried to understand the solution to the error, but I have had a few days off tunnel vision with this issue.
I have tried my best to link my issue with other threads, but have been lost for a few days. I did get some form of sprint finish with setting up a {get { return } } with a property but due to the setup of the code when serializing I couldn't do that. Instead I've tried to put the file outputted in a simple location and tried desalinizing it based on the file location.
ImageModeration image1 = JsonConvert.DeserializeObject<ImageModeration>(File.ReadAllText(#"C:\ModerationOutput.json"));
// deserialize JSON directly from a file
using (StreamReader file = File.OpenText(#"C:\ModerationOutput.json"))
{
JsonSerializer serializer = new JsonSerializer();
ImageModeration image2 = (ImageModeration)serializer.Deserialize(file, typeof(ImageModeration));
}
Here is my json file
[
{
"ImageUrl": "URL",
"ImageModeration": {
"CacheID": "396a972f-79ae-4b31-a54c-0ba3314318fa_637026883058218816",
"Result": false,
"TrackingId": "UKS_ibiza_464a60be-f57d-4ee1-aa37-13d04f151fdd_ContentModerator.F0_4ae15371-36c9-4cb2-8e21-83381a29432c",
"AdultClassificationScore": 0.0048455675132572651,
"IsImageAdultClassified": false,
"RacyClassificationScore": 0.011258091777563095,
"IsImageRacyClassified": false,
"AdvancedInfo": [
{
"Key": "ImageDownloadTimeInMs",
"Value": "37"
},
{
"Key": "ImageSizeInBytes",
"Value": "34854"
}
],
"Status": {
"Code": 3000,
"Description": "OK",
"Exception": null
}
},
"TextDetection": null,
"FaceDetection": null
}
]
This error comes from the first line of code.
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the
current JSON array (e.g. [1,2,3]) into type
'convertingJSON.Program+ImageModeration' because the type requires a
JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix
this error either change the JSON to a JSON object (e.g.
{"name":"value"}) or change the deserialized type to an array or a
type that implements a collection interface (e.g. ICollection, IList)
like List that can be deserialized from a JSON array.
JsonArrayAttribute can also be added to the type to force it to
deserialize from a JSON array. Path '', line 1, position 1.'
Specific to your JSON string that you have posted, you can refer to the following code snippet to deserialize your string into its respective components.I am using the Newtonsoft JSON library which is a popular high-performance JSON framework for .NET. A working example can be found at: https://dotnetfiddle.net/RmXNHM
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
string json=#"[{'ImageUrl':'URL','ImageModeration':{'CacheID':'396a972f-79ae-4b31-a54c-0ba3314318fa_637026883058218816','Result':false,'TrackingId':'UKS_ibiza_464a60be-f57d-4ee1-aa37-13d04f151fdd_ContentModerator.F0_4ae15371-36c9-4cb2-8e21-83381a29432c','AdultClassificationScore':0.004845567513257265,'IsImageAdultClassified':false,'RacyClassificationScore':0.011258091777563095,'IsImageRacyClassified':false,'AdvancedInfo':[{'Key':'ImageDownloadTimeInMs','Value':'37'},{'Key':'ImageSizeInBytes','Value':'34854'}],'Status':{'Code':3000,'Description':'OK','Exception':null}},'TextDetection':null,'FaceDetection':null}]";
var Sresponse = JsonConvert.DeserializeObject<List<RootObject>>(json);
foreach(var value1 in Sresponse)
{
Console.WriteLine(value1.ImageUrl);
Console.WriteLine(value1.ImageModeration.CacheID);
}
}
}
public class AdvancedInfo
{
public string Key { get; set; }
public string Value { get; set; }
}
public class Status
{
public int Code { get; set; }
public string Description { get; set; }
public object Exception { get; set; }
}
public class ImageModeration
{
public string CacheID { get; set; }
public bool Result { get; set; }
public string TrackingId { get; set; }
public double AdultClassificationScore { get; set; }
public bool IsImageAdultClassified { get; set; }
public double RacyClassificationScore { get; set; }
public bool IsImageRacyClassified { get; set; }
public List<AdvancedInfo> AdvancedInfo { get; set; }
public Status Status { get; set; }
}
public class RootObject
{
public string ImageUrl { get; set; }
public ImageModeration ImageModeration { get; set; }
public object TextDetection { get; set; }
public object FaceDetection { get; set; }
}
Output:
URL
396a972f-79ae-4b31-a54c-0ba3314318fa_637026883058218816
Use this site to convert you're JSON to a C# object and then deserialize to it.
According to the error it seems you may have been missing a property i.e. the object does not correspond to the JSON
My web service receives data-filtering values in JSON format. Here is an example of how the filtering criteria is sent:
var jsonString = {
"startDate":"2015-01-19T15:04:54.897Z",
"endDate":"2016-01-19T15:04:54.897Z",
"filterParams":{
"facilityIds":
[
{"ID":1,"charID":"1","Description":"Health Group Umbrella Organization","DoubleValue1":35.009803,"DoubleValue2":85.21,"StringValue1":""},
{"ID":2,"charID":"2","Description":"Main Hospital Organization","DoubleValue1":35.04,"DoubleValue2":89.3,"StringValue1":""},
{"ID":3,"charID":"3","Description":"Regional Medical Center","DoubleValue1":35.04,"DoubleValue2":89.30,"StringValue1":""}
],
"GenderIds":[{"ID":0,"charID":"F","Description":"Female","DoubleValue1":0,"DoubleValue2":0,"StringValue1":""}],
"AgeRangeIds":[{"ID":4,"charID":"4","Description":"30 - 34","DoubleValue1":0,"DoubleValue2":0,"StringValue1":""}],
"HomeownerIds":[{"ID":7,"charID":"7","Description":"More Likely Owner 1","DoubleValue1":0,"DoubleValue2":0,"StringValue1":""}],
"IncomeRangeIds":[{"ID":3,"charID":"3","Description":"$30,001 - $40,000","DoubleValue1":0,"DoubleValue2":0,"StringValue1":""}],
"HasChildrenIds":[{"ID":0,"charID":"N","Description":"No","DoubleValue1":0,"DoubleValue2":0,"StringValue1":null}],
"EncoutnerTypesIds":
[
{"ID":2,"charID":"2","Description":"Ambulatory","DoubleValue1":0,"DoubleValue2":0,"StringValue1":""},
{"ID":1,"charID":"1","Description":"InPatient","DoubleValue1":0,"DoubleValue2":0,"StringValue1":""},
{"ID":3,"charID":"3","Description":"Emergency","DoubleValue1":0,"DoubleValue2":0,"StringValue1":""},
{"ID":4,"charID":"4","Description":"Office Visit","DoubleValue1":0,"DoubleValue2":0,"StringValue1":""}
]
}
}
I'm able to pull out the startDate and endDate no problem:
var jsonValues = jsonSerializer.Deserialize<Dictionary<string, object>>(jsonString);
DateTime startDate = DateTime.Parse(jsonValues["startDate"] as string);
DateTime endDate = DateTime.Parse(jsonValues["endDate"] as string);
However, I just can't seem to figure out how to handle the "filterParams" portion of the JSON. It should map to the class structure:
public class FilterModel
{
public int ID { get; set; }
public char charID { get; set; }
public string Description { get; set; }
public double DoubleValue1 { get; set; }
public double DoubleValue2 { get; set; }
public string StringValue1 { get; set; }
}
the following statement populates the variable with the correct data but I'm unable to access the values.
var filterParams = jsonValues["filterParams"];
I need to somehow deserialize the data into a Dictionary<string, FilterModel> but the Deserialize method requires a string param and filterParams is an object.
You don't need to deserialize each property manually...
JavaScriptSerializer
You can deserialize it directly to a complex object using the native JavaScriptSerializer:
RootObject obj = new JavaScriptSerializer().Deserialize<RootObject>(jsonString);
Newtonsoft Json
Or as #Wobbles suggested, you can use the Json.Net also known as Newtonsoft Json:
RootObject obj = JsonConvert.DeserializeObject<RootObject>(jsonString);
It is faster and has more features than JavaScriptSerializer as you can see here.
You can use something like this (Very specific, but it must works):
-> This is using Newtonsoft
public class YourJson
{
public DateTime startDate;
public DateTime endDate;
public FilterParams filterParams;
}
public class FilterParams
{
public __ID[] facilityIds;
public __ID[] GenderIds;
public __ID[] AgeRangeIds;
public __ID[] HomeownerIds;
public __ID[] IncomeRangeIds;
public __ID[] HasChildrenIds;
public __ID[] EncoutnerTypesIds;
}
public class __ID
{
public int ID;
public char charID;
public string Description;
public double DoubleValue1;
public double DoubleValue2;
public String StringValue1;
}
var yourJson = JsonConvert.DeserializeObject<YourJson>(json);