反序列化递归JSON对象

时间:2016-05-10 11:53:01

标签: c# json recursion serialization json.net

我有一个表示查询表达式的递归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做到这一点?

1 个答案:

答案 0 :(得分:1)

定义这样的类:

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