C# 分组读取JSON数据
我有JSON数据(有车的家庭),我正在尝试读取JSON数据。子集如下所示:C# 分组读取JSON数据,c#,json,parsing,C#,Json,Parsing,我有JSON数据(有车的家庭),我正在尝试读取JSON数据。子集如下所示: [ { "car":[ "Honda Civic", "Toyota Camry" ] }, { "car":[ "Honda Civic" ] }, { "car":[ "BMW 760", "Mercedes S", "S
[
{
"car":[
"Honda Civic",
"Toyota Camry"
]
},
{
"car":[
"Honda Civic"
]
},
{
"car":[
"BMW 760",
"Mercedes S",
"Smart Car"
]
},
{
"car":[
"Honda Odyssey",
"Tesla X"
]
},
{
"car":[
"BMW 760"
]
},
{
"car":[
"Honda Odyssey",
"Tesla X"
]
},
{
"car":[
"BMW 760"
]
},
{
"car":[
"Toyota Camry",
"Honda Civic"
]
}
]
class Household
{
public List<string> Cars { get; set; }
}
var cars = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Dictionary<string, string[]>>>(json);
List<Household> households = (
from h in cars
select new Household()
{
Cars = h["car"].ToList()
}
).ToList();
当我使用以下逻辑读取文件时,它被成功读取。(我使用的是Newtonsoft.Json
)
我面临两个问题:
allCars
- 只有宝马760的家庭是3个
- 与思域和凯美瑞是2
- 只有Civic是1,以此类推
我尝试执行上面提到的操作,但没有成功。您必须首先展平嵌套的汽车名称列表,然后将它们分组以获得所需的输出
class Program
{
static void Main(string[] args)
{
string carsData = @"
[
{
'car':[
'Honda Civic',
'Toyota Camry'
]
},
{
'car':[
'Honda Civic'
]
},
{
'car':[
'BMW 760',
'Mercedes S',
'Smart Car'
]
},
{
'car':[
'Honda Odyssey',
'Tesla X'
]
},
{
'car':[
'BMW 760'
]
},
{
'car':[
'Honda Odyssey',
'Tesla X'
]
},
{
'car':[
'BMW 760'
]
},
{
'car':[
'Toyota Camry',
'Honda Civic'
]
}
]
";
List<Car> allCars = JsonConvert.DeserializeObject<List<Car>>(carsData);
// Flatten all the car names first then group them
var carDistributions = allCars.SelectMany(x => x.CarNames)
.GroupBy(x => x, x => x, (key, x) => new
{
CarName = key,
Count = x.Count()
})
.ToList();
foreach (var carDistribution in carDistributions)
{
Console.WriteLine(carDistribution.CarName + " " + carDistribution.Count);
}
}
}
public class Car
{
[JsonProperty("Car")]
public List<string> CarNames { get; set; }
}
首先,使用或粘贴特殊选项为json解析创建模型
PasteSpecial选项可以在编辑->粘贴特殊->将JSON粘贴为类中找到
这将为您提供解析json字符串的正确模型
public class Car
{
public List<string> car { get; set; }
}
此JSON结果的本机数据类型为
List
。您可以使用以下命令直接解析它:
var cars = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Dictionary<string, string[]>>>(json);
恕我直言,Newtonsoft的反序列化类应该尽可能简单。Newtonsoft功能强大,在反序列化过程中可以做很多事情,但是越简单,如果将来需要更改数据结构,就越容易进行修改。反序列化后的映射函数用于将数据转换为对应用程序有用的内容。我认为这是一个很好的SoC原则
奖金回合
private void CreateReport(List<Household> households)
{
//get all unique cars
List<string> cars = households.SelectMany(h => h.Cars).Distinct().OrderBy(c => c).ToList();
foreach(string c in cars)
{
Console.WriteLine("Households with {0}: {1}", c, HouseholdsWith(households, c));
Console.WriteLine("Households with only {0}: {1}", c, HouseholdsWithOnly(households, c));
}
//Get each unique pair
var pairs = households.Where(h => h.Cars.Count > 1).SelectMany(h =>
{
List<Tuple<string, string>> innerpairs = new List<Tuple<string, string>>();
for (int i = 0; i < h.Cars.Count - 1; i++)
{
for (int j = i + 1; j < h.Cars.Count; j++)
{
if (string.Compare(h.Cars[i], h.Cars[j]) < 0)
{
innerpairs.Add(new Tuple<string, string>(h.Cars[i], h.Cars[j]));
}
else
{
innerpairs.Add(new Tuple<string, string>(h.Cars[j], h.Cars[i]));
}
}
}
return innerpairs;
}).Distinct().ToList();
foreach (var p in pairs)
{
Console.WriteLine("Households with {0} and {1}: {2}", p.Item1, p.Item2, HouseholdsWith(households, p.Item1, p.Item2));
}
}
你为什么要使用arraylist@KunalMukherjee因为我可以动态构建它,并认为它可能有助于增加汽车。“只有宝马760的家庭”是2。2户只有2户,但3户至少有1户。
List<Car> allCars = JsonConvert.DeserializeObject<List<Car>>(sJSON);
int count = allCars.SelectMany(x => x.car).Where(x => x == "Honda Civic").Count(); // It will return 3 as a result
var cars = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Dictionary<string, string[]>>>(json);
private int HouseholdWith(List<Dictionary<string, string[]>> cars, string car1)
{
return cars.Count(household => household["car"].Any(c => c == car1));
}
private int HouseholdWith(List<Dictionary<string, string[]>> cars, string car1, string car2)
{
return cars.Count(household => household["car"].Any(c => c == car1) && household["car"].Any(c => c == car2));
}
private int HouseholdWithOnly(List<Dictionary<string, string[]>> cars, string car)
{
return cars.Count(household => household["car"].All(c => c == car));
}
class Household
{
public List<string> Cars { get; set; }
}
var cars = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Dictionary<string, string[]>>>(json);
List<Household> households = (
from h in cars
select new Household()
{
Cars = h["car"].ToList()
}
).ToList();
private int HouseholdsWith(List<Household> households, string car1)
{
return households.Count(h => h.Cars.Any(c => c == car1));
}
private int HouseholdsWith(List<Household> households, string car1, string car2)
{
return households.Count(h => h.Cars.Any(c => c == car1) && h.Cars.Any(c => c == car2));
}
private int HouseholdsWithOnly(List<Household> households, string car)
{
return households.Count(h => h.Cars.All(c => c == car));
}
Console.WriteLine("Households who have only BMW 760 are {0}", HouseholdsWithOnly(households, "BMW 760"));
//Households who have only BMW 760 are 2
Console.WriteLine("Households who have BMW 760 are {0}", HouseholdsWith(households, "BMW 760"));
//Households who have BMW 760 are 3
Console.WriteLine("Households with Civic and Camry are {0}", HouseholdsWith(households, "Honda Civic", "Toyota Camry"));
//Households with Civic and Camry are 2
Console.WriteLine("Households with only Civic is {0}", HouseholdsWithOnly(households, "Honda Civic"));
//Households with only Civic is 1
private void CreateReport(List<Household> households)
{
//get all unique cars
List<string> cars = households.SelectMany(h => h.Cars).Distinct().OrderBy(c => c).ToList();
foreach(string c in cars)
{
Console.WriteLine("Households with {0}: {1}", c, HouseholdsWith(households, c));
Console.WriteLine("Households with only {0}: {1}", c, HouseholdsWithOnly(households, c));
}
//Get each unique pair
var pairs = households.Where(h => h.Cars.Count > 1).SelectMany(h =>
{
List<Tuple<string, string>> innerpairs = new List<Tuple<string, string>>();
for (int i = 0; i < h.Cars.Count - 1; i++)
{
for (int j = i + 1; j < h.Cars.Count; j++)
{
if (string.Compare(h.Cars[i], h.Cars[j]) < 0)
{
innerpairs.Add(new Tuple<string, string>(h.Cars[i], h.Cars[j]));
}
else
{
innerpairs.Add(new Tuple<string, string>(h.Cars[j], h.Cars[i]));
}
}
}
return innerpairs;
}).Distinct().ToList();
foreach (var p in pairs)
{
Console.WriteLine("Households with {0} and {1}: {2}", p.Item1, p.Item2, HouseholdsWith(households, p.Item1, p.Item2));
}
}
Households with BMW 760: 3
Households with only BMW 760: 2
Households with Honda Civic: 3
Households with only Honda Civic: 1
Households with Honda Odyssey: 2
Households with only Honda Odyssey: 0
Households with Mercedes S: 1
Households with only Mercedes S: 0
Households with Smart Car: 1
Households with only Smart Car: 0
Households with Tesla X: 2
Households with only Tesla X: 0
Households with Toyota Camry: 2
Households with only Toyota Camry: 0
Households with Honda Civic and Toyota Camry: 2
Households with BMW 760 and Mercedes S: 1
Households with BMW 760 and Smart Car: 1
Households with Mercedes S and Smart Car: 1
Households with Honda Odyssey and Tesla X: 2