1

I want to deserialize following json

{ "variableName": "Current", "dataFormat": "FLOAT" }

and want to get the 'dataformat' directly as datatype of a variable.

In this case something like

public string VariableName {get; set;}
public float VariableValue {get; set;}
// or 
public boolean VariableValue {get;set;}
// or 
public object VariableValue {get; set;}

Any suggestions or not possible?

Gabe
  • 109
  • 4
  • Where is variable value in JSON? – kat1330 Feb 28 '17 at 23:24
  • Yes, thats my problem... For VariableName i take the left side, for the datatype I want to use the right side. The VariableValue could also have another name... Understandable? – Gabe Feb 28 '17 at 23:25
  • Not sure that I understand. In JSON `dataFormat` represents data type. In C# `VariableValue ` should represent some data like `5.4`. But I am not seeing where is your value in JSON. – kat1330 Mar 01 '17 at 00:35

1 Answers1

0

You could encapsulate a Type Converter in your getter for VariableValue. E.g.

void Main()
{
    const string json = @"    { 
        'variableName': 'Current',
        'dataFormat': 'System.Double',
        'dataValue' : '1.2e3' //scientific notation
    }";
    var v = JsonConvert.DeserializeObject<Variable>(json);

    Console.WriteLine($"Value={v.VariableValue}, Type={v.VariableValue.GetType().Name}");
    // Value=1200, Type=Double
    // Note that it converted the string "1.2e3" to a proper numerical value of 1200.
    // And recognises that VariableValue is a Double instead of our declared Object.
}

public class Variable
{
    // From JSON:
    public string VariableName { get; set; }
    public string DataFormat { get; set; }
    public string DataValue { get; set; }

    // Here be magic:
    public object VariableValue
    {
        get
        {
            /*  This assumes that 'DataFormat' is a valid .NET type like System.Double.
                Otherwise, you'll need to translate them first.
                E.g. "FLOAT" => "System.Single" 
                     "INT"   => "System.Int32", etc
            */
            var actualType = Type.GetType(DataFormat, true, true);
            return Convert.ChangeType(DataValue, actualType);
        }
    }
}

Edit: for the conversion from type aliases to a framework type (e.g. float to System.Single), this answer has a list of them.

Community
  • 1
  • 1
NPras
  • 3,135
  • 15
  • 29