我有一个像这样的递归JSON对象,表示一个查询表达式:
{
"where": {
"operator": "AND",
"left": {
"operator": "=",
"$fieldRef": "requestor",
"value": "@me"
},
"right": {
"operator": "=",
"$fieldRef": "state",
"value": "Closed"
}
}
}
JSON层次结构中也可以出现更多的对象。这里有一个更复杂的例子:
{
"where": {
"operator": "OR",
"left": {
"operator": "=",
"$fieldRef": "id",
"value": "1234"
},
"right": {
"operator": "OR",
"left": {
"operator": "=",
"$fieldRef": "orgId",
"value": "6757"
},
"right": {
"operator": "AND",
"left": {
"operator": "STARTSWITH",
"$fieldRef": "firstname",
"value": "D"
},
"right": {
"operator": "=",
"$fieldRef": "state",
"value": "Closed"
}
}
}
}
}
我希望能够将这个JSON反序列化为一些类,更新数据,然后再序列化回JSON。如何使用Json.NET完成此操作?
这样定义类:
class Query
{
[JsonProperty("where")]
public Clause Where { get; set; }
}
class Clause
{
[JsonProperty("operator")]
public string Operator { get; set; }
[JsonProperty("left")]
public Clause Left { get; set; }
[JsonProperty("right")]
public Clause Right { get; set; }
[JsonProperty("$fieldref")]
public string FieldRef { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
然后你可以像这样反序列化:
Query q = JsonConvert.DeserializeObject<Query>(json);
您可以序列化回JSON,如下所示:
JsonSerializerSettings settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
Formatting = Formatting.Indented
};
json = JsonConvert.SerializeObject(q, settings);
以下是一个简单的演示:https://dotnetfiddle.net/qqAj2v