2017-07-17 43 views
-4

我有一個動態的數組的json數組本質上可以是動態的。我想反序列化成一個類。在 「數據類型」 標籤決定C#類memeber的數據類型反序列化一個動態的JSON到一個C#類

[{ 
    "model": "DeviceModel.DeviceInstance", 
    "name": "My-Device", 
    "variables": { 
    "Variable1": { 
     "SubVariable1": { 
     "DataType": "Double", 
     "Unit": "V", 
     "High": "3.5", 
     "Low": "3.2", 
     "Nominal": "3.3" 
     }, 
     "SubVariable2": { 
     "DataType": "Double", 
     "Unit": "A", 
     "High": "10" 
     } 
    }, 
    "Variable2": { 
     "DataType": "Int", 
     "Unit": "bytes", 
     "Max": "100000", 
     "Low": "10000", 
     "LowLow": "500" 
    } 
    }, 
    "properties": { 
    "ConstantProperty": { 
     "PropertyName": { 
     "DataType": "String", 
     "Value": "12-34561" 
     } 
    } 
    } 
} 
] 
+1

DataType是一個字符串。沒有不同的類型。 *值*描述不同的數據類型。您應該描述反序列化的結果會是什麼樣子以避免混淆。 –

+0

儘管數據類型是基於文本bool,float或string的字符串,但對象需要反序列化爲特定類型 –

+1

@VivekRao這是什麼意思?你如何將「測試」反序列化爲bool? –

回答

1

我對你的問題的解決辦法和解決以下發現偉大的工程 裁判: 1. http://json2csharp.com/#

2. JavaScriptSerializer.Deserialize array

public class SubVariable1 
    { 
     public string DataType { get; set; } 
     public string Unit { get; set; } 
     public string High { get; set; } 
     public string Low { get; set; } 
     public string Nominal { get; set; } 
    } 

    public class SubVariable2 
    { 
     public string DataType { get; set; } 
     public string Unit { get; set; } 
     public string High { get; set; } 
    } 

    public class Variable1 
    { 
     public SubVariable1 SubVariable1 { get; set; } 
     public SubVariable2 SubVariable2 { get; set; } 
    } 

    public class Variable2 
    { 
     public string DataType { get; set; } 
     public string Unit { get; set; } 
     public string Max { get; set; } 
     public string Low { get; set; } 
     public string LowLow { get; set; } 
    } 

    public class Variables 
    { 
     public Variable1 Variable1 { get; set; } 
     public Variable2 Variable2 { get; set; } 
    } 

    public class PropertyName 
    { 
     public string DataType { get; set; } 
     public string Value { get; set; } 
    } 

    public class ConstantProperty 
    { 
     public PropertyName PropertyName { get; set; } 
    } 

    public class Properties 
    { 
     public ConstantProperty ConstantProperty { get; set; } 
    } 

    public class RootObject 
    { 
     public string model { get; set; } 
     public string name { get; set; } 
     public Variables variables { get; set; } 
     public Properties properties { get; set; } 
    } 

    class Stackoverflow 
    { 
     static void Main(string[] args) 
     { 

      string strJSONData = "Your JSON Data";// Either read from string of file source 
      System.Web.Script.Serialization.JavaScriptSerializer jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); 
      List<RootObject> objRootObjectList = jsSerializer.Deserialize<List<RootObject>>(strJSONData); 
Console.ReadLine(); 
     } 
    } 

我希望這會幫助你。

相關問題