1

I have JSON data coming as

{ "ResultOne":{ "Value1":2,"Value2":3,"Type":"SimpleAdd","Result":5}}

Few other JSON data as

{ "ResultTwo":{ "Value1":2,"Value2":3,"Type":"SimpleSubtract","Result":-1}}

{ "ResultThree":{ "Value1":2,"Value2":3,"Type":"SimpleMultiply","Result":6}}

and so on.

So basically, the inner JSON remains the same, while the outer value keeps changing. I use json2csharp.com to generate class (to make things easier).

    public class ResultOne
{
    public int Value1 { get; set; }
    public int Value2 { get; set; }
    public string Type { get; set; }
    public int Result { get; set; }
}

public class RootObject
{
    public ResultOne ResultOne { get; set; }
}

How can I create a class in C# to reuse code (instead of creating multiple properties for each results in Rootobject, may be reflection ? any pointers in the right direction is helpful. thanks.

EDIT: I am actually using a Delegate to call the server to get JSON response.

 delegate Task<RootObject> Operation(int Value1, int Value2);

The delegate is used to pass in as variable in the method below. This Operation opMeth will determine the type of result that we receive. That will depend on the user input. so I cannot use ResultOne, but need a generic result in the method below.

private async Task<string> DoSomeOp(int Value1, int Value2, Operation opMeth)
    {
        var opResult = await opMeth(Value1, Value1);
        string resultValue = opResult.ResultOne.Result;
        return resultValue;
    }
3
  • 4
    You can deserialize it to Dictionary<string,ResultClass> Commented Jun 5, 2017 at 19:13
  • @SirRufo - can you provide an example for that. Commented Jun 7, 2017 at 20:43
  • JsonConvert.DeserializeObject<Dictionary<string,ResultClass>>( jsonResultString ); Commented Jun 7, 2017 at 20:53

1 Answer 1

1

Well, though your JSON is pretty simple and represent simple Dictionary type, you can avoid creating any classes at all, by using dynamic:

using Newtonsoft.Json;
using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var str = "{ \"ResultTwo\":{ \"Value1\":2,\"Value2\":3,\"Type\":\"SimpleSubtract\",\"Result\":-1}}";

            dynamic des = JsonConvert.DeserializeObject(str);
            var val = (int)des.ResultTwo.Value1;
            Console.WriteLine(val);
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your reply. updated the question with more details. see if it can provide more insights into why I am creating a class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.