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();
Related
I am a novice in C# and I am having issues reading a JSON file.
The JSON file follows this format:
{
"info": {
"year": 2020,
"version": "1.0",
"description": "fake description",
"date_created": "2020-04-31T20:32:11.8958473Z"
},
"licenses": [
{
"name": "fake name",
"id": 2020
}
],
"images": [
{
"id": 1,
"width": 1280,
"height": 720,
"filename": "filename1.jpeg",
"license": 1
},
{
"id": 2,
"width": 1280,
"height": 720,
"filename": "filename2.jpeg",
"license": 2
},
...
For now I am trying to read the Images section in the JSON file. Here is my class for it:
public class Images
{
[JsonProperty("id")]
public int id { get; set; }
[JsonProperty("width")]
public int width { get; set; }
[JsonProperty("height")]
public int height { get; set; }
[JsonProperty("filename")]
public string filename { get; set; }
[JsonProperty("license")]
public int license { get; set; }
}
public class Image_json
{
[JsonProperty("images")]
public Image Image_json { get; set; }
}
In my main class, I try deserializing it here:
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
namespace C__Playground
{
public class read_json
{
static void Main(string[] args)
{
using (StreamReader r = new StreamReader("COCOExport.json"))
{
string json = r.ReadToEnd();
var test1 = JsonConvert.DeserializeObject<List<Image_json>(json);
}
}
}
}
When I try to run the program, I get this message:
Unhandled exception. Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[C__Playground.Image_jsonJson]' 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.
I have been following this post here.
I tried using the solution here but it returns empty or I receive a null error. Any insights?
Your problem should be here:
public class Image_json
{
[JsonProperty("images")]
public Image_json Image_json { get; set; }
}
This property is of type Image_json, which is the same as the containing class. You need a collection of Images. Could be an array or a List<Images>.
public class Image_json
{
[JsonProperty("images")]
public List<Images> Image_json { get; set; }
}
BTW, the Images class should be called Image since it holds a single image, not a collection of them.
Please find below code.
Class Images:
public class Images
{
[JsonProperty("id")]
public int id { get; set; }
[JsonProperty("width")]
public int width { get; set; }
[JsonProperty("height")]
public int height { get; set; }
[JsonProperty("filename")]
public string filename { get; set; }
[JsonProperty("license")]
public int license { get; set; }
}
class ImageJson:
public class ImageJson
{
[JsonProperty("images")]
public List<Images> Image_json // We shoild use list of images
{
get; set;
}
}
To test output:
using (StreamReader r = new StreamReader("COCOExport.json"))
{
string json = r.ReadToEnd();
var test1 = JsonConvert.DeserializeObject<ImageJson>(json);
foreach(var output in test1.Image_json)
{
Console.WriteLine(output.id);
Console.WriteLine(output.width);
Console.WriteLine(output.height);
Console.WriteLine(output.filename);
Console.WriteLine(output.license);
}
Console.ReadLine();
}
It is alwasy good practice to use PascalCasing for Properties.
Ex:)
[JsonProperty("id")]
public int Id { get; set; }
Please find solution here. Explained in a video
https://www.youtube.com/watch?v=nHtdReIhvag
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
I have API endpoint, that returning my JSON Object
Here is it
{
"results": [
{
"id": 182,
"title": "1-Day Private Beijing Tour to Tian'anmen Square, Forbidden City and Badaling Great Wall",
"price": "162",
"duration": "8",
"duration_type": "1",
"cover_image": {
"id": 308,
"img_path": "upload/images",
"img_file": "6d637884086151b30fe12db52fbaf5eb.jpg",
"status": "",
"created_at": "2018-02-27 02:25:36",
"updated_at": "2018-02-27 02:25:36",
"destination_id": "182",
"is_cover": "0",
"url": "https://api.xplorpal.com/upload/images/300x300/6d637884086151b30fe12db52fbaf5eb.jpg"
}
},
{
"id": 183,
"title": "One Day Private Beijing Tour to Mutianyu Great Wall and Summer Palace ",
"price": "197",
"duration": "8",
"duration_type": "1",
"cover_image": {
"id": 305,
"img_path": "upload/images",
"img_file": "1f8a09ddffb80ef9232f3511893ae5c4.jpg",
"status": "",
"created_at": "2018-02-27 02:22:19",
"updated_at": "2018-03-01 23:01:55",
"destination_id": "183",
"is_cover": "0",
"url": "https://api.xplorpal.com/upload/images/300x300/1f8a09ddffb80ef9232f3511893ae5c4.jpg"
}
}
]
}
I need to deserialize it
So I wrote this model
public class CoverImage
{
public int id { get; set; }
public string img_path { get; set; }
public string img_file { get; set; }
public string status { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public string destination_id { get; set; }
public string is_cover { get; set; }
public string url { get; set; }
}
public class Result
{
public int id { get; set; }
public string title { get; set; }
public string price { get; set; }
public string duration { get; set; }
public string duration_type { get; set; }
public CoverImage cover_image { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
}
And trying to this like this
var responseExperiences = JsonConvert.DeserializeObject<IEnumerable<RootObject>>(content);
But when I run the project, I have this error:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.IEnumerable`1[TravelApp.Models.GettingExperiences+Results]' 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.
How I can fix this?
your JSON shows one object result corresponding to RootObject.
But you are trying to deserialize an array (IEnumerable<>) of RootObject
You should use this to deserialiaze the JSON showed :
JsonConvert.DeserializeObject<RootObject>(content);
Your API returns an object with a single property named result, not a collection. You should deserialize into a RootObject object.
Your api return single object named result not a collection you simply need to desearilize as a single object like.
var responseExperiences = JsonConvert.DeserializeObject<RootObject>(content);
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.
I'm trying to deserialize a file that contains data set of JSON objects that are not separated by commas
{
"passages": [
{
"is_selected": 1,
"url": "http://someUrl.com",
"passage_text": "someTextHere"
},
{
"is_selected": 0,
"url": "http://someUrl.com",
"passage_text": "someTextHere""
},
],
"query_id": 9749,
"answers": ["Here is the answer"],
"query_type": "description",
"query": "Here is my query"
}
{
"passages": [
{
"is_selected": 0,
"url": "http://someAnotherUrl.com",
"passage_text": "someAnotherTextHere"
},
{
"is_selected": 1,
"url": "http://someAnotherUrl.com",
"passage_text": "someAnotherTextHere""
},
],
"query_id": 0564,
"answers": ["Here is the another answer"],
"query_type": "another description",
"query": "Here is my another query"
}
I am trying to use this code with Newtonsoft.JSON deserialization but it returns an exception
"An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll
Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[JsonParser.DataSet]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly."
public class DataSet
{
public List<Passage> passages { get; set; }
public int query_id { get; set; }
public List<string> answers { get; set; }
public string query_type { get; set; }
public string query { get; set; }
public int Count { get; internal set; }
}
public class Passage
{
public int is_selected { get; set; }
public Uri url { get; set; }
public string passage_text { get; set; }
}
class Program
{
public static string jsonFileLocation = #"C:\my.json";
static void Main(string[] args)
{
using (StreamReader file = File.OpenText(jsonFileLocation))
{
JsonSerializer serializer = new JsonSerializer();
List<DataSet> data = (List<DataSet>)serializer.Deserialize(file, typeof(List<DataSet>));
}
}
}
I do not think it's a good idea to place commas and brackets manually to bring the file to JSON format because this file contains several thousand records.
Have you any ideas how to parse and deserialize this file?
If the file is consistent in that each JSON node is separated by a new line character, you could first stream the file into a System.String and replace all instances of:
}
{
with:
},
{
Then, deserialize the JSON string. This is just one idea.