0

I have a question, we have an ASP.NET web app that can service multiple clients.

The only difference is that the app needs to convert some JSON string into a .NET object of type <T> in order to pass that object to a WCF service.

For that purpose I am using Newtonsoft.Json.Converter:

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

The problem is that that type <T> is unknown at design time. But after the deserialization I need to have a generic strongly-typed object so that I can pass it to WCF service. The reason for that is WCF service is different for each client, and the parameter input may have a different structure for each client.

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

Here input is of type CalcEngine.CalcInputTypes. For clientA and clientB CalcEngine.CalcInputTypes may have different structure.

What is the best way to accomplish that?

Thanks.

monstro
  • 6,254
  • 10
  • 65
  • 111
  • How are you detecting which client to call? When you know at compile time which client you are calling you know at compile time what to fill in for `T` – Scott Chamberlain Apr 07 '15 at 16:53
  • Hi Scott, WCF ABC configuration (in web.config) determines what service to call. The problem was with the passing type. But it changes now, I verified with the team, the type of passed parameter alwasy has the same name, but different structure. And here its a different story, since in code I dont need to know the structure in order to Deserialize JSON string into that object, it will automatically copy values for matched properties. – monstro Apr 07 '15 at 20:02

1 Answers1

0

For example, suppose your input could be either of the following two JSON messages:

{
  "type": "Gizmo",
  "value": {
    "name": "Banana"
  }
}

{
  "type": "Widget",
  "value": {
    "widget_id": 7,
    "data": [4, 2, 6, 3]
  }
}

You could decide how to deserialize the incoming message by inspecting the type and then deserializing the value to a known .NET type. You can do this using JToken:

var input = JToken.Parse(jsonInput);
var type = input["type"].ToObject<string>();
if (type == "Gizmo")
{
    var gizmo = input["value"].ToObject<Gizmo>();
}
else if (type == "Widget")
{
    var widget = input["value"].ToObject<Widget>();
}
Timothy Shields
  • 75,459
  • 18
  • 120
  • 173
  • Oh, I cannot have any specific type reference in Code! For example - that "Gizmo" thing is never known, I cannot assume that we'll have predetermined types. This can only be configured thru .config file or somehow else, but not in code. I was thinking about dependency injection, but not sure. – monstro Apr 07 '15 at 17:06
  • Thanks, Timothy, sorry, looks like the requirements have changed, type of target object doesnt change, it has the same name, but different structure. In this case its a totally different story. Thanks. – monstro Apr 07 '15 at 19:58