How do you handle an object of a specific type that can only be determined at runtime?

Here's a query I have: We're working on an ASP.NET web application that is designed to cater to multiple clients.

The crucial aspect is the app's need to transform specific JSON strings into .NET object of type <T> so that it can be passed to a WCF service.

To achieve this, we are utilizing Newtonsoft.Json.Converter:

T input = JsonConvert.DeserializeObject<T>(jsonInput);

The challenge lies in the fact that the type <T> remains unknown during the design phase. However, following deserialization, there arises a requirement for a generic strongly-typed object to enable seamless utilization with the WCF service. This necessity emerges due to varying structures of the WCF service across different clients, leading to differing parameter requirements for each client.

var client = new CalcEngine.CalculatorClient();
var input = new CalcEngine.CalcInputTypes();
var result = client.Calculate(input);

In this case, the 'input' is identified as CalcEngine.CalcInputTypes. Notably, CalcEngine.CalcInputTypes could exhibit distinct structures for clientA and clientB.

What would be the optimal approach to resolving this?

Many thanks!

Answer №1

For instance, let's say you have two JSON messages as possible input:

{
  "category": "Fruit",
  "details": {
    "name": "Apple"
  }
}

{
  "category": "Appliance",
  "details": {
    "appliance_id": 12,
    "features": ["smart", "energy efficient"]
  }
}

To handle these incoming messages, you can examine the category field and then deserialize the details to a known object in Python. You can accomplish this using json.loads:

data = json.loads(json_input)
category = data["category"]
if category == "Fruit":
    fruit = Fruit(**data["details"])
elif category == "Appliance":
    appliance = Appliance(**data["details"])

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

Access JSON data and file in the Model-View-Controller framework

Below is my client-side code for sending a JSON object and a file to MVC using JQuery ajax: var formData = new FormData(); formData.append('logo', logoImg); var objArr = []; objArr.push({"id": id, "name": userName}); //JSON obj formData.append ...

Specification for Application Input: Receiving input information for a specific method

Is there a recommended method for visually representing the input data structure required for a server application? I am working on specifying the correct input data that the server will receive via an http post request. The data being sent is a complex js ...

Can structured logging in NLog be utilized without the need for templated messages?

Up until now, our team has been utilizing NLog version 4.4.12 without structured logging. However, for achieving structured logging, we have been relying on https://www.nuget.org/packages/NLog.StructuredLogging.Json/. An advantage of using this extension ...

Error: Unable to access the 'questionText' property as it is undefined

I encountered an error message stating that my "questionText" could not be read or is not defined. The issue seems to arise in the first code block where I use "questionText", while the intention is to drag it in the second code block. Is there a mistake ...

Serializing and deserializing Tuples with Jackson in Scala using JSON

Here, I am attempting to perform a round-trip operation on a Tuple2 using the jackson-module-scala library in Scala 2.10.4. However, it seems that the serializer encodes the Tuple2 as a JSON array, leading to issues with deserialization. Why does this ha ...

Error: The data retrieval from a JSON file failed due to a type error. The program expected list indices to be

I am attempting to extract all latitude and longitude values from the provided JSON data. Below is the code snippet: import urllib.parse import requests raw_json = 'http://live.ksmobile.net/live/getreplayvideos?userid=' print() userid = 73589 ...

Failure parsing occurred when attempting to make an HTTP POST request from Angular to a PHP server

When I try to consume the PHP endpoint from Postman, everything works fine. But when I attempt to do the same from an Angular post request, I encounter an error - Http failure during parsing for. Even though I have double-checked my code and it all seems c ...

Explore the information stored in two different arrays

Currently, I'm trying to access and load data from 2 arrays. I've managed to successfully load the items array within the first array. However, when attempting to access the data inside the second array, it fails to load. The JSON response conta ...

What is the best way to eliminate the additional square bracket from a JSON file containing multiple arrays?

Seeking JSON data from an array, I encountered an issue with an extra square bracket appearing in the output. After attempting $episode[0] = $podcast->getPodcastByCategoryId($id);, only partial data was retrieved, corresponding to the first iteration. ...

Performing a wildcard search to replace deep child values and merging them back into the original JSON using JQ

Can someone help me with a JSON manipulation issue similar to the one discussed in this post about Unix jq parsing wildcards? I want to change the value of "c": "text1" to "c": "newtext", while also merging the modif ...

Reduce the identification number within a JSON array following the removal of an item

Within my local storage, I maintain a dynamic array. Each entry is accompanied by an ID that increments sequentially. If a user opts to delete an entry, it should be removed from the array while ensuring that the IDs remain in ascending order. For example: ...

``There seems to be a problem with decoding JSON data in Swift, as some information

I am currently working on querying the NASA image API with Swift 4. After testing my network request and decoding setup using JSONPlaceholder, everything was functioning properly. However, when I switched to the NASA API URL and JSON data structure, I enco ...

Error message states: "An error occurred while attempting to parse the json file

Currently enrolled in the Python Mega Course on Udemy, I'm diligently following the instructions to code all the recommended applications. However, while working on Application 2 - Creating Webmaps with Python and Folium, I encountered the following e ...

Proper approach for mapping JSON data to a table using the Fetch API in a React.js application

Struggling to map some elements of JSON to a Table in Customers.jsx, but can't seem to figure out the correct way. How do I properly insert my Fetch Method into Customers.jsx? Specifically managing the renderBody part and the bodyData={/The JsonData/} ...

Address Book on Rails

Hello, I'm relatively new to this and would be grateful for any assistance. My goal is to utilize the data saved by a user in their address book, and then offer them the option to use that address for delivery. Below is my Address controller: class A ...

Efficiently loading data using lazy loading in jsTree

I have been facing a challenge with dynamically loading the nodes of a jtree upon expansion. The limited documentation I could find is located towards the end of this specific page. Several solutions involve creating nodes individually using a loop, simil ...

Retrieve data from a JSON file

I have a JSON file containing various player data, and I need to extract the "Name" field from it. { "player": [ { "Position": "TEST", "Name": "TEST", "Squad_No": "TEST", "Club": "TEST", "Age": "TEST" }, ...

Exploring the combination of search functionality using json and PHP language with SQL integration

I developed a search system with 4 pages/steps. The first 3 pages consist of checkboxes for filtering, and I am facing an issue with creating these checkboxes based on JSON data. Currently, I can only read the names from the JSON data to create the checkbo ...

Learn the process for downloading media files from WhatsApp API that are sent by users

Currently, I am developing a chatbot specifically for WhatsApp using the 360dialog platform, which allows me to integrate with the WhatsApp Business API. Whenever a client sends a message, I receive a JSON object in my application logs: { "messag ...

The world of visual content and data interchange: AS3 graphics

Prior to this, I inquired about action script 3 Json request However, my main query is centered around transforming an image into a JSON object. Any suggestions? Thanks! ...