Does C# have a library for parsing multi-level cascading JSON?

后端 未结 2 1790
無奈伤痛
無奈伤痛 2020-12-19 02:02

Is there a library (C# preferred) to resolve what I would call multi-level cascading JSON?

Here is an example of what I mean: (Pseudocode/C#)

<
2条回答
  •  半阙折子戏
    2020-12-19 02:31

    This is super easy using the excellent JSON.NET library. This method combines objects with properties that are are strings, numbers, or objects.

    public static string Cascade(params string[] jsonArray)
    {
        JObject result = new JObject();
        foreach (string json in jsonArray)
        {
            JObject parsed = JObject.Parse(json);
            foreach (var property in parsed)
                result[property.Key] = property.Value;
        }
        return result.ToString();
    }
    

    Result, given your example:

    {
      "firstName": "Albert",
      "lastName": "Smith",
      "phone": "12345"
    }
    

    Edit in response to your updated question:

    By adjusting this solution to work recursively, you can merge child objects. The following example will match your expected results (except for the array). You will be able to easily extend this solution to merge arrays (JArray) in a manner similar to how it merges objects (JObject).

    public static string Cascade(params string[] jsonArray)
    {
        JObject result = new JObject();
        foreach (string json in jsonArray)
        {
            JObject parsed = JObject.Parse(json);
            Merge(result, parsed);
        }
        return result.ToString();
    }
    
    private static void Merge(JObject receiver, JObject donor)
    {
        foreach (var property in donor)
        {
            JObject receiverValue = receiver[property.Key] as JObject;
            JObject donorValue = property.Value as JObject;
            if (receiverValue != null && donorValue != null)
                Merge(receiverValue, donorValue);
            else
                receiver[property.Key] = property.Value;
        }
    }
    

提交回复
热议问题