1

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.'

  • 1
    Please provide json or its part. – Alex Sham Aug 30 '19 at 09:08
  • How large is your ModerationOutput.json file? Could you post its content? – MindSwipe Aug 30 '19 at 09:09
  • Your JSON is probably not formatted like an object `{}` but rather an array of values `[]`. Be good to be able to see an example of how your JSON is structured. – Nico Aug 30 '19 at 09:11
  • As nico_c says, the error message is fairly clear - you're trying to deserialise to a single object, whereas it seems your JSON contains an array (i.e. a list of objects). If you showed us a sample of the JSON we could probably confirm that for you. – ADyson Aug 30 '19 at 09:13
  • 3
    Your root object should be a collection type such as `List`, see [Cannot deserialize the JSON array (e.g. `[1,2,3]`) into type ' ' because type requires JSON object (e.g. {“name”:“value”}) to deserialize correctl)](https://stackoverflow.com/q/22557559) (of which this is probably a duplicate, though we can't say for sure without a JSON sample.) – dbc Aug 30 '19 at 09:13
  • I have edited the post to have my JSON contents – jamesscales-code Aug 30 '19 at 09:36
  • Still, as @jdc commented, your json root is a list (`[...]`), you need to deserialize into a list of something, probably `List`. – Lasse V. Karlsen Aug 30 '19 at 09:39
  • Yes, it's a duplicate, you need to deserialize to a list as shown here: https://dotnetfiddle.net/OxP2Tr – dbc Aug 30 '19 at 09:44

2 Answers2

1

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

AMunim
  • 992
  • 6
  • 13
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
Rahul Sharma
  • 7,768
  • 2
  • 28
  • 54
  • This would help me if my JSON file contents never changed, but I'm required to read the contents from the file due to the values changing. I'm still going through the previous answers to get my answer. Thanks. – jamesscales-code Aug 30 '19 at 10:05
  • @jamesscales-code This will work even if your JSON file contents are changed but the base model structure is same. You can try this out by reading from your file. If the model structure changes, you can use the `dynamic` property to get your data. – Rahul Sharma Aug 30 '19 at 10:07
  • 1
    Thank you @Rahul Sharma this has resolved my issue. I changed the json contents to File.ReadAllText(@"C:\ModerationOutput.json"); – jamesscales-code Aug 30 '19 at 10:24