2017-07-17 45 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(); 
     } 
    } 

我希望这会帮助你。

相关问题