I JavaScript.Serializer.Deserializer
verwenden ein komplexes JSON-Objekt deserialisieren, wie unten:Deserialisieren ein komplexes JSON-Objekt
{
"name": "rule 1",
"enabled": true,
"conditions": [{
"type": "time",
"time": "17:23:10",
"days": "125"
}, {
"type": "sensor",
"uid": "10.2.0.1",
"setpoint1": 12,
"setpoint2": 18,
"criterion": 1
}, {
"type": "sensor",
"uid": "10.3.0.1",
"setpoint1": 12,
"setpoint2": 18,
"criterion": 2
}],
"actions": {
"period": 100,
"single": false,
"act": [{
"type": "on",
"uid": "10.1.0.1"
}, {
"type": "sms",
"message": "Hello World"
}]
}
}
Und ich möchte einige Klassen konvertieren es, wie unten:
public class Rule
{
public string name { get; set; }
public bool enabled { get; set; }
public List<Condition> conditions { get; set; }
public List<Action> actions { get; set; }
}
public class Condition
{
public string type { get; set; }
public string uid { get; set; }
public DateTime? time { get; set; }
public string days { get; set; }
public double setpoint1 { get; set; }
public double setpoint2 { get; set; }
public int criterion { get; set; }
}
public class Action
{
public int period { get; set; }
public bool single { get; set; }
public List<Act> act { get; set; }
}
public class Act
{
public string type { get; set; }
public string uid { get; set; }
public string message { get; set; }
}
Die Deserialisierung snippet:
json = new JavaScriptSerializer();
Rule rule = (json.Deserialize<Rule>(jsonStr));
Wenn ich die Rule
Klasse zu vereinfachen und erklären, conditions
und actions
so einfach strings
, es funktioniert gut.
Aber wenn ich die Klassen wie oben verwenden, wirft es eine Ausnahme:
Kann Objekt vom Typ ‚System.String‘ umwandeln geben ‚System.Collections.Generic.List`1 [IoTWebApplication.Condition ] '
Ihr JSON ist kein gültiges JSON - bitte überprüfen Sie es h http://jsonlint.com und posten Sie die richtige JSON –
Sie haben Recht, aber ich eingerückt, dass für eine bessere Lesbarkeit – Amir
Einzug ist in Ordnung, aber es ist immer noch ungültig - Möchten Sie ein ungültiges JSON deserialisieren -> das ist nicht möglich –