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
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 5 objects nested json file. In nutshell, the json file has the following pattern:
{
"Object1": {
"Object2": {
"Object3": {
"Object4": [
"Object5",
"Object5",
"Object5"
]
}
}
}
}
Edit: Previously I had inconsistent naming. I have revised the names to reflect the comments that I was given.
I would like to deserialize the json into a C# object as follows
using System;
using Newtonsoft.Json;
namespace Example
{
class Program
{
public class Object1
{
public string Name { get; set; }
public Object2[] Object2s { get; set; }
}
public sealed class Object2
{
public string Name { get; set; }
public Object3[] Object3s { get; set; }
}
public class Object3
{
public string Name { get; set; }
public Object4 [] Object4s { get; set; }
}
public class Object4
{
public string Name { get; set; }
public Object5 [] Object5s { get; set; }
}
public class Object5
{
public string Name { get; set; }
}
static void Main(string[] args)
{
string json = "{ \"Object1\": { \"Object2\": { \"Object3\": { \"Object4\": [ \"Value1\",\"Value2\",\"Value3\" ] } }}}";
Object1[] object1s = JsonConvert.DeserializeObject<Object1[]>(json);
Console.WriteLine(object1s[0].Name);
}
}
}
Unfortunately, when I run it, it results in the following exception:
Newtonsoft.Json.JsonSerializationException
HResult=0x80131500
Message=Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'Example.Program+Object1[]' 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<T>) 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.
Path 'Object1', line 1, position 15.
Is there any way this can be achieved without resorting to looping through the json tree?
The exception is thrown, because you are trying to deserialize an json object into an array. This will not work
Object1[] object1s = JsonConvert.DeserializeObject<Object1[]>(json);
This will work:
Object1 object1 = JsonConvert.DeserializeObject<Object1>(json);
You will also need to change either the json or the class model, because again the current json contains objects and the class model expects arrays. This code is the updated class model to fit the json file:
public class Object1
{
public string Name { get; set; }
public Object2 Object2 { get; set; }
}
public sealed class Object2
{
public string Name { get; set; }
public Object3 Object3 { get; set; }
}
public class Object3
{
public string Name { get; set; }
public string[] Object4 { get; set; }
}
One more issue is in the JSON, there are two properties of the same name inside a json object:
"Object4": [
"Object5",
"Object5",
"Object5"
],
"Object4": [
"Object5",
"Object5",
"Object5"
]
If you want to have multiple objects Object4 inside Object3, you could use an array:
{
"Object1": {
"Object2": {
"Object3": {
"Object4": [{
"Object5": [{}, {}, {}
]
}, {
"Object5": [{}, {}, {}
]
}
],
}
}
}
}
I am new to Newtonsoft.Json so please excuse my ignorance - however I am coming up against this issue when trying to Deserialize the following Json to either a c# object or indeed manually.
The Json is
{
"travellerInfo": [
{
"passengerData": {
"travellerInformation": {
"passenger": [
{
"type": "ADT",
"firstName": "MARY MRS"
},
{
"type": "INF",
"firstName": "JOSHUA"
}
],
"traveller": {
"surname": "SMITH",
"quantity": "2"
}
}
}
},
{
"passengerData": {
"travellerInformation": {
"passenger": {
"type": "ADT",
"firstName": "JOHN MR"
},
"traveller": {
"surname": "SMITH",
"quantity": "1"
}
}
}
}
]
}
So as you can see, on the first 'passenger' item, this returns as an Array, however on the second 'passenger' item, it doesn't return as an array, just a single block. I am not in control of the Json being sent to me - it comes from an external system. My C# classes are
public class Passenger
{
public string type { get; set; }
public string firstName { get; set; }
}
public class Traveller
{
public string surname { get; set; }
public string quantity { get; set; }
}
public class TravellerInformation
{
public List<Passenger> passenger { get; set; }
public Traveller traveller { get; set; }
}
public class PassengerData
{
public TravellerInformation travellerInformation { get; set; }
}
public class TravellerInfo
{
public PassengerData passengerData { get; set; }
}
and I call
var example = JsonConvert.DeserializeObject<TravellerInfo>(jsonString);
I am getting the error
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Script1.TravellerInfo' 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<T> 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 'travellerInfo', line 57, position 20.
I tried putting a [JsonArray] attribute on the Passenger class to force it to deserialise as an array/list, but same error occured as I think the underlying item is a JProperty instead of a JObject.
So how can I get this to work when the ["passenger"] can come back as both an Array and Single object ?
Cheers in Advance
You can try deserialize it as dynamic and then do some checks to types. Check if it is IEnumerable.
That should do the job.
Try this. Replace List<Passenger> with object passenger in TravellerInformation:
public class Traveller
{
public string surname { get; set; }
public string quantity { get; set; }
}
public class TravellerInformation
{
public object passenger { get; set; }
public Traveller traveller { get; set; }
}
public class PassengerData
{
public TravellerInformation travellerInformation { get; set; }
}
public class TravellerInfo
{
public PassengerData passengerData { get; set; }
}
And call this by passing List<TravellerInfo> instead of TravellerInfo:
var example = JsonConvert.DeserializeObject<List<TravellerInfo>>(jsonString);
Also for these cases you can use this service which automatically creates C# classes from JSON objects, so you don't have to worry about correctness.
I am getting following JSON data
[{"id":"1","text":"System Admin","target":{"jQuery1710835279177001846":12},"checked":true,"state":"open"},
{"id":"2","text":"HRMS","target":{"jQuery1710835279177001846":34},"checked":false,"state":"open"},
{"id":"3","text":"SDBMS","target":{"jQuery1710835279177001846":42},"checked":false},
{"id":"8","text":"Admin","target":{"jQuery1710835279177001846":43},"checked":false},
{"id":"9","text":"My test Admin","target":{"jQuery1710835279177001846":44},"checked":false,"state":"open"},
{"id":"24","text":"ModuleName","target":{"jQuery1710835279177001846":46},"checked":false,"state":"open"}]
which try to parsed using Json.Net using strongly type
this are my property class
public class testclass
{
public string id { get; set; }
public string text { get; set; }
public string #checked { get; set; }
public string state { get; set; }
public target jQuery1710835279177001846 { get; set; }
}
public class testclass2
{
public List<testclass> testclass1 { get; set; }
}
public class target
{
public string jQuery1710835279177001846 { get; set; }
}
and here i am trying to access the data i am getting exception
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'QuexstERP.Web.UI.Areas.SysAdmin.Controllers.testclass' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
My controller code look like
public void Test(string Name, object modeldata)
{
var obj = JsonConvert.DeserializeObject<testclass>(Name);
}
Any idea how to solve this issue in C#
Your Json string looks to have serialized array object in it because it contains [ ]. It means you have a Json string which is formed after serialization of array object. So you need to deserialized into array object, so try this
var obj = JsonConvert.DeserializeObject<List<testclass>>(jsonString);
you have Array of TestClass. so it should be like this.
var model= JsonConvert.DeserializeObject<List<testclass>>(Name);
why you are using JSonConvert ? in MVC3 you can do like this
return Json(yourmodel,JsonRequestBehavior.AllowGet);
Your json objects are like this
{
"id":"1",
"text":"System Admin",
"target":{
"jQuery1710835279177001846":12
},
"checked":true,
"state":"open"
}
It should be like this I guess
{
"id":"1",
"text":"System Admin",
"jQuery1710835279177001846":12,
"checked":true,
"state":"open"
}
i have the following json string (jsonString)
[
{
"name":"Fruits",
"references":[
{"stream":{"type":"reference","size":"original",id":"1"}},
],
"arts":[
{"stream":{"type":"art","size":"original","id":"4"}},
{"stream":{"type":"art","size":"medium","id":"9"}},
]
}
]
and the following C# objects
class Item
{
public string Name { get; set; }
public List<Stream> References { get; set; }
public List<Stream> Arts { get; set; }
public Item()
{
}
}
class Stream
{
public string Type { get; set; }
public string Size { get; set; }
public string Id { get; set; }
public Stream()
{
}
}
and the following code
Item item = JsonConvert.DeserializeObject<Item>(jsonString);
when I run the code, it creteas the correct number of references and arts, but each stream has null value (type = null, size = null).
is it posible to do this json.net deserializeobject method or should I manually deserialize ?
EDIT: Okay, ignore the previous answer. The problem is that your arrays (references and arts) contain objects which in turn contain the relevant data. Basically you've got one layer of wrapping too many. For example, this JSON works fine:
[
{
"name":"Fruits",
"references":[
{"Type":"reference","Size":"original","Id":"1"},
],
"arts":[
{"Type":"art","Size":"original","id":"4"},
{"type":"art","size":"medium","id":"9"},
]
}
]
If you can't change the JSON, you may need to introduce a new wrapper type into your object model:
public class StreamWrapper
{
public Stream Stream { get; set; }
}
Then make your Item class have List<StreamWrapper> variables instead of List<Stream>. Does that help?