有可能与两个jsons相交吗?

时间:2018-02-21 14:36:17

标签: c# json json.net

我试图在两个JSON之间的c#中进行交叉。

例如,给定下一个对象和操作相交:

{
"Property 1" : "Value 1",
"Property 2" : "Value 2",
"Property 3" : "Value 3",
"Property 4" : "Value 4"
}

相交

{
"Property 1" : "Value 1",
"Property 2" : "Value 2",
"Property 6" : "Value 6"
}

应该等于:

{
"Property 1" : "Value 1",
"Property 2" : "Value 2"
}

我只是为了清晰而放了一个简单的json,但是json对象可以是任何格式,复杂而简单。

2 个答案:

答案 0 :(得分:0)

您可以将json解析为Dictionary并从那里与它相交。

我使用了这个json字符串

 string Json1 = @"
{""Property 1"" : ""Value 1"",
""Property 2"" : ""Value 2"",
""Property 3"" : ""Value 3"",
""Property 4"" : ""Value 4""
}";

 string Json2 = @"{
""Property 1"" : ""Value 1"",
""Property 2"" : ""Value 2"",
""Property 6"" : ""Value 6""
}";
 var Result = IntersectedJson(Json1, Json2);
 Console.WriteLine(Result);
 Console.Read();

 public static string IntersectedJson(string Json1, string Json2)
    {
        var Dictionary1 = JsonConvert.DeserializeObject<Dictionary<string, string>>(Json1);
        var Dictionary2 = JsonConvert.DeserializeObject<Dictionary<string, string>>(Json2);
        var result = Dictionary1.Keys.Intersect(Dictionary2.Keys).ToDictionary(t => t, t => Dictionary1[t]);
        return JsonConvert.SerializeObject(result);
    }

这是我得到的结果

{"Property 1":"Value 1","Property 2":"Value 2"}

我正在使用NewtonSoft.Json进行序列化。只要属性名称是唯一的,它就应该工作。希望这会有所帮助。

答案 1 :(得分:0)

你也可以使用LINQ,它应该有更好的性能......

        var json1 = JsonConvert.DeserializeObject<Dictionary<string, string>>(
            @"{
            'Property 1': 'Value 1',
            'Property 2': 'Value 2',
            'Property 3': 'Value 3',
            'Property 4': 'Value 4'
            }");
        var json2 = JsonConvert.DeserializeObject<Dictionary<string, string>>(
            @"{ 
            'Property 1': 'Value 1',
            'Property 2': 'Value 2'
            }");

        // that will do the trick
        var result = json1.Where(x => json2.ContainsKey(x.Key))
                          .ToDictionary(x => x.Key, x => x.Value);

        var jsonResult = JsonConvert.SerializeObject(result);
相关问题