c#判断json的数据是否有重复
时间: 2023-12-10 19:05:34 浏览: 36
判断JSON数据是否有重复,可以按照以下步骤进行:
1. 读取JSON文件,并将JSON数据解析为一个对象数组。
2. 对于每个JSON对象,将其转换为字符串,并计算其哈希值(可以使用C#的SHA256Managed类),将哈希值存储到一个HashSet中。
3. 如果HashSet中已经存在该哈希值,则说明该JSON数据是重复的。
示例代码:
```csharp
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public static bool HasDuplicateJson(string filePath)
{
HashSet<string> hashSet = new HashSet<string>();
using (StreamReader reader = new StreamReader(filePath))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
object jsonObject = JsonConvert.DeserializeObject(line);
string jsonString = JsonConvert.SerializeObject(jsonObject, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
byte[] jsonData = Encoding.UTF8.GetBytes(jsonString);
byte[] hashData = new SHA256Managed().ComputeHash(jsonData);
string hashString = Encoding.UTF8.GetString(hashData);
if (hashSet.Contains(hashString))
{
return true;
}
hashSet.Add(hashString);
}
}
return false;
}
```
该函数接受一个文件路径作为输入,返回一个布尔值,表示文件中是否存在重复的JSON数据。函数内部遍历文件中的每一行JSON数据,并计算其哈希值,判断是否存在重复。函数可以根据实际情况进行修改。