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

后端 未结 2 1786
無奈伤痛
無奈伤痛 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:29

    Not that I know of. For the simple case, you can use any JSON library, then merge the dictionaries with a solution like this one. E.g. using Newtonsoft/Json.NET:

    Dictionary<String, String> dict1, dict2, dict3, merged;
    dict1 = JsonConvert.DeserializeObject<Dictionary<string,string>>(json1);
    dict2 = JsonConvert.DeserializeObject<Dictionary<string,string>>(json2);
    dict3 = JsonConvert.DeserializeObject<Dictionary<string,string>>(json3);
    merged = Merge(new[]{dict1, dict2, dict3});
    

    Obviously, in production code you'd factor out the redundant lines.

    0 讨论(0)
  • 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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题