An attempt to convert an object of type 'Newtonsoft.Json.Linq.JObject' to another type has failed

I'm currently using JSON.NET and reflection to parse data into specific properties.

property.SetValue(comInstance, field.Value);

However, I encounter an ArgumentException on this line:

An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll

Additional information: Object of type 'Newtonsoft.Json.Linq.JObject' cannot be converted to type 'Microsoft.Xna.Framework.Vector2'.

This issue seems related to my custom JsonConverter for handling Vector2 types:

public class Vector2Converter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(Vector2));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject jsonObject = JObject.Load(reader);
        var properties = jsonObject.Properties().ToList();
        return new Vector2
        {
            X = (float)properties[0].Value,
            Y = (float)properties[1].Value
        };
    }
    
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        Vector2 v = (Vector2)value;
        writer.WriteStartObject();
        writer.WritePropertyName("X");
        serializer.Serialize(writer, v.X);
        writer.WritePropertyName("Y");
        serializer.Serialize(writer, v.Y);
        writer.WriteEndObject();
        
    }
}

It appears that the write method is being called but not the read method during deserialization.

Deserialize operation looks like this:

JsonConvert.DeserializeObject<EntityJson>(json, JsonUtility.Settings);

The JsonUility.Settings includes the Vector2Converter.

And for serialization, it's done as follows:

JsonConvert.SerializeObject(entityJson, Formatting.Indented, JsonUtility.Settings);

The JSON field structure also seems correct:

"Center": {
      "X": 116.0,
      "Y": 65.0
    },

If anyone has any insights or solutions, please let me know. Thank you!

Edit:

internal class EntityJson
{
    public string Name { get; set; }
    public Dictionary<string, ComponentJson> Components { get; set; }

    public EntityJson()
    {
        Components = new Dictionary<string, ComponentJson>();
    }

    public Entity ToEntity()
    {
        Entity entity = new Entity(Name);

        foreach(KeyValuePair<string, ComponentJson> com in Components)
        {
            ObjectHandle handle = Activator.CreateInstance(com.Value.Namespace, com.Value.Namespace +"."+ com.Key);
            Object handleValue = handle.Unwrap();
            Component comInstance = (Component)handleValue;

            foreach(KeyValuePair<string, object> field in com.Value.Fields)
            {
                PropertyInfo property = comInstance.GetType().GetProperty(field.Key, 
                    BindingFlags.NonPublic | 
                    BindingFlags.Public | 
                    BindingFlags.Instance);

                property.SetValue(comInstance, field.Value); // <-- field.Value
            }

            entity.AddUnsafe(comInstance);
        }

        return entity;
    }
}

In this context, the field.value is a JObject instead of a Vector2, leading to the casting exception mentioned above.

The object cannot be casted.

Answer №1

After some troubleshooting, I was able to fix it by following these steps:

object result = field.Value;
if (field.Value.GetType() == typeof(JObject))
{
      JToken token = (JToken)field.Value;
      result = token.ToObject(property.PropertyType, JsonSerializer.Create(JsonUtility.Settings));
}
else
{
      result = Convert.ChangeType(result, property.PropertyType);
}

property.SetValue(comInstance, result); 

Can we consider this as a reliable solution?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determine the total number of arrays present in the JSON data

I'm currently working on a straightforward AngularJS project, and here's the code I have so far: This is my view: <tr ng-repeat="metering in meterings"> <td>1</td> <td>{{metering.d.SerialNumber}}</td> ...

Error encountered in PhantomJS when using Selenium: TypeError - The function _getTagName(currWindow) is not a constructor and is undefined

Utilizing CSharp and Selenium, I designed an automated application for a testing website with the help of PhantomJS. However, I encountered an issue while attempting to use SendKeys("values") on the website. <section id="login"> <form class= ...

how to use serializeArray() to create an array with named keys

I am struggling with a piece of HTML code : <input type="checkbox" name="search-form[filters][category][12]" value="cat-12" autocomplete="off" checked="checked" /> <input type="checkbox" name="search-form[filters][category][14]" value="cat-14" au ...

Tips for modifying the JSON format within a Spring and Angular project

I am utilizing Spring for the backend and Angular for the frontend. Below is my REST code: @GetMapping(path = "/endpoint") public @ResponseBody Iterable<Relations> getGraphGivenEndpointId(@RequestParam(value = "id") int id) { return ...

Creating an array in ReactJS by mapping a JSON object: A step-by-step guide

I've got a JSON object that I need to parse and create two separate arrays. One array will contain the ART field data, while the other will store the SALIDA field values. Click here to see the JSON data For more information on ReactJS const DisplayT ...

Having trouble retrieving information from a nested JSON array within a JSON object using JavaScript

I am facing a challenge with extracting specific information from a JSON object that contains an array nested inside. Even though I have experience working with JSON arrays, this particular object is proving to be tricky. For example, when attempting to r ...

Parsing JSON array values with dynamic keys into JSON_TABLE with consistent columns

I am facing a challenge with JSON data being imported into my MariaDB/MYSQL database using Airbyte from an API query. I have been using JSON_TABLE to extract the JSON into columns, which has been working quite well. However, I recently noticed that there i ...

Converting JSON data into a Pandas dataframe

I am encountering an issue with converting JSON formatted data to a Pandas dataframe. The JSON data I have is structured as shown below and is stored in the variable active_assets - Asset({ 'class': 'us_equity', 'easy_to_borr ...

What is the best way to obtain an array of JSON objects using PHP?

I've been working on code to retrieve data in JSON format, but it's not exactly in the format I need. Can someone assist me in resolving this issue? while ($row = $get_postid->fetch_array()) { $comment_id[]=$row[& ...

Extract information from a JSON string and present it on the screen

I am a complete novice when it comes to D3 (with very little experience in JS). Here are the lines of code I am working with: <script type='text/javascript'> data ='{"mpg":21,"cyl":6,"disp":160,"hp":110,"drat":3.9,"wt":2.62,"qsec":16. ...

Creating a Python script that fetches all items from the API Server

If you were tasked with creating a Python web client to interact with an online supermarket's API, here are the details you would need: Base URL = Your goal is to write a Python program that fetches all the products from the API Server and then disp ...

Unable to access image from JSON within Mobile Angular Ui utilizing Angular Js

Currently, I am able to retrieve various data from JSON such as Price and Display Order, but I am facing difficulty in fetching the image. HTML: <div ng-controller="chooseProductDescription"> <div ng-repeat="cat in productDescrip ...

Using C# to send HttpWebRequest with a JSON POST request header

While translating a JSON API into C# Methods, I came across an issue with the JSON RPC API (POST) that states: All other methods require the result from authentication ( = sessionId), either through a path parameter ;jsessionid=644AFBF2C1B592B68C6B04938B ...

Retrieving form data from within the resource error callback scope

For my client-side validation on submit, I am calling a resource if the form is valid. On success, everything works fine. However, when encountering an error handler, I also perform server-side validation on my data transfer object bean which contains Hibe ...

Filtering values with spaces using JQ

I'm facing an issue where I need to select and filter a value that contains a space in it. My attempt involves using a for loop, but unfortunately, I'm not getting any output with this approach. I even tried utilizing --arg name "$i", however, th ...

Python's nested if conditions allow for more complex conditions to be

In a specific scenario, I am required to validate certain conditions within the provided JSON data and then take action accordingly. You can view the json data here. The condition that needs to be checked is as follows: Iterate through the JSON and ident ...

Displaying a specific number of items from an array using Rails

Looking to showcase only 4 items from an array at a time? Simply click "Next" to reveal the next set of 4 items. Here's the code: <table> <tr> <th></th> <th>3</th> <th&g ...

Converting child dictionaries with identical key names to CSV format using Python's DictWriter

Looking for a solution to format JSON files into CSV files? I have a specific structure in my json file, as shown below: [ {"A":{"value":1}, "B":{"value":2}}, {"A":{"value":9}, "B":{&quo ...

How can one save a text value element from a cascading list in ASP.NET MVC?

I have recently started learning about javascript, jquery, and ajax. In my model, I have defined the following classes: namespace hiophop.Models { public class CarMake { public class Category { public int CategoryID { g ...

What is the best way to use cURL in a shell script to send a request with custom

When attempting to run a CURL statement, I successfully received the desired response: curl -s -POST --header 'Content-Type: application/json' 'http://www.dummy.com/projectname/page_relevance' -d '{"query": "q_string", "results": ...