我有一个不同类型的对象(无架构)的json列表。 但是,每一行都包含结构的类型。我需要根据他们的类型对其进行分组。我需要对这个 Json 进行分组。输入如下
var result = [{ "firstName":"John", "lastName":"Doe", "Type":"Person" },
{ "fruit":"apple", "Type":"Diet" },
{ "length":100, "width":60, "height":30,, "Type":"Measure" },
{ "firstName":"Shivang", "lastName":"Mittal", "Type":"Person" }]
预期输出:
var persons= [{ "firstName":"John", "lastName":"Doe", "Type":"Person" },
{ "firstName":"Shivang", "lastName":"Mittal", "Type":"Person" }];
var Diets = [{ "fruit":"apple", "Type":"Diet" }];
var Measures = [{ "length":100, "width":60, "height":30,, "Type":"" }];
如何根据它们在 c# 中的类型对其进行分组?
不使用强类型对象/更改架构:
var jarray = JArray.Parse(@"[{ ""firstName"":""John"", ""lastName"":""Doe"", ""Type"":""Person"" },
{ ""fruit"":""apple"", ""Type"":""Diet"" },
{ ""length"":100, ""width"":60, ""height"":30, ""Type"":""Measure"" },
{ ""firstName"":""Shivang"", ""lastName"":""Mittal"", ""Type"":""Person"" }]");
var query = jarray
.GroupBy(g => g["Type"])
.Select(g => string.Format("var {0}={1};{2}", g.Key, new JArray(g.ToList()), Environment.NewLine));
string result = string.Join(string.Empty, query);
更好的是
更改您的 JSON 格式:
{
"Customer": [{"firstName":"John", "lastName":"Doe", "Type":"Person" }],
"Fruit": [{"fruit":"apple", "Type":"Diet" }],
"Length": [{"length":100, "width":60, "height":30, "Type":"Measure" }]
}
然后就很容易了
public class JsonType()
{
public CustomerType Customer {get; set;}
public FruitType Fruit {get; set;}
public LengthType Length {get; set;}
}
public class CustomerType()
{
public string firstName {get; set;}
public string lastName {get; set;}
public string Type {get; set;}
}
public class FruitType()
{
public string fruit {get; set;}
public string Type {get; set;}
}
等。。。
var result = JsonConvert.DeserializeObject<JsonType>(yourJson);