2017-02-28 60 views
1

我想反序列化JSON之後反序列化的數據類型與Json.net

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

,並希望得到「DATAFORMAT」直接作爲變量的數據類型。

在這種情況下,像

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

任何建議或不可能的?

+0

JSON中的變量值在哪裏? – kat1330

+0

是的,那是我的問題...對於VariableName我採取左側,爲我想使用右側的數據類型。 VariableValue也可以有另一個名字......可以理解嗎? – Gabe

+0

不知道我的理解。在JSON中'dataFormat'表示數據類型。在C#中'VariableValue'應該代表一些像'5.4'這樣的數據。但是我沒有看到你在JSON中的價值。 – kat1330

回答

0

你可以在你的getter中爲VariableValue封裝一個Type Converter。例如。

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); 
     } 
    } 
} 

編輯:用於從類型別名到一個框架類型(例如floatSystem.Single),this answer has a list of them轉換。