C# C语言中model/HashMap/Dictionary的JSON字符串#
我有:C# C语言中model/HashMap/Dictionary的JSON字符串#,c#,json,dictionary,hashmap,C#,Json,Dictionary,Hashmap,我有: { "One": [ { "ID": 1, "name": "s" }, { "categoryID": 2, "name": "c" } ], "Two": [ { "ID": 3, "name": "l" } ], "Three": [ { "ID": 8, "name": "s&P" }, { "ID": 52, "name": "BB" } ] } 我想: 将此JSON带到任何对象(如JObject) 在不同条件下过滤JSON(如
{
"One": [
{
"ID": 1,
"name": "s"
},
{
"categoryID": 2,
"name": "c"
}
],
"Two": [
{
"ID": 3,
"name": "l"
}
],
"Three": [
{
"ID": 8,
"name": "s&P"
},
{
"ID": 52,
"name": "BB"
}
]
}
我想:
class Model
{
public int Id;
public string name;
}
class MainModel
{
public string mainName;
public List<Model> categories;
}
类模型
{
公共int Id;
公共字符串名称;
}
类主模型
{
公共字符串mainName;
公开名单类别;
}
并使用这些模型:
List<MainModel> m = json_serializer.DeserializeObject(jsonString);
List m=json\u序列化程序。反序列化对象(jsonString);
任何帮助都将不胜感激。以下内容将允许您将JSON反序列化到字典并对其进行筛选。这使用了Newtonsoft.JSON Nuget包,但这是相当常见的。代码发布在下面。在这里可以找到工作示例
使用系统;
使用Newtonsoft.Json;
使用System.Collections.Generic;
使用System.Linq;
公共课程
{
公共静态void Main()
{
var json=“{\'One\\”:[{\'ID\':1,\'name\':\'s\',{\'categoryID\':2,\'name\':\'c\',\'Two\':[{\'ID\':3,\'name\':\'l\',\'Three\':[{\'ID\':8,\'name\'s\':\'s&P\',{\'ID\'52,\'name\':'BB\'};
var deserialized=JsonConvert.DeserializeObject(json);
Console.WriteLine(反序列化[“一”][0].name);
Console.WriteLine(“过滤器以s开头”);
var filtered=反序列化。SelectMany(item=>item.Value)。其中(innerItem=>innerItem.name.StartsWith(“s”);
foreach(过滤后的变量项){
Console.WriteLine(项目名称);
}
}
公共类模型{
公共int ID{get;set;}
公共字符串名称{get;set;}
public int categoryID{get;set;}
}
}
我编写此代码时假设:
、One
和Two
是一个Three
——它从main类别
中序列化为KeyValuePair
。长类型名称,呃?如果您想经常使用结果字典,请添加以下内容:JProperty
2.创建using MainCategories = System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<JsonDeSerializtionTest.SubCategory>>;
函数:反序列化(字符串json)
- 您可以轻松地将JSON序列化回字符串表示形式。示例:
string jsonIn ="{\"One\":[{\"ID\":1,\"name\":\"s\"}," + "{\"categoryID\":2,\"name\":\"c\"}]," + "\"Two\":[{\"ID\":3,\"name\":\"l\"}]," + "\"Three\":[{\"ID\":8,\"name\":\"s&P\"}," + "{\"ID\":52,\"name\":\"BB\"}]}"; MainCategories desrializedJson = Deserialize(jsonIn); MainCategories filtered = desrializedJson.WhereNameStartsWith("s"); string jsonOut = JsonConvert.SerializeObject(desrializedJson, Formatting.None); Debug.Assert(jsonOut == jsonIn); //true
- 在访问
/Id
时,无需进行空检查CategoryId
- 我的最爱:对属性名使用C#语法
- 我不知道。这是一种糊状物,忘了它吧 在更改JSON结构时可能会遇到困难(尽管我可能会认为这会让事情变得更容易)
是可选的,用于在使用LINQ时简化操作Parent
是一个枚举,用于确定是否找到了DataTypes
或ID
,如果需要这些信息,还可以序列化适当的属性(相同的双向转换)categoryID
var jObj=JObject.Parse(jsonString);
现在你有了不止一个字典。我试过字典:Dictionary dct=(Dictionary>)json\u序列化程序。反序列化对象(json);我得到了无效的强制转换异常。很明显,您将得到无效的强制转换异常。您的模型与JSON不一致
public class SubCategory
{
[JsonIgnore]
public DataTypes DataType { get; set; }
[JsonIgnore]
public string Parent { get; set; }
[JsonProperty("ID")]
public int Id { get; set; }
[JsonProperty("categoryID")]
public int CategoryId => Id;
[JsonProperty("name")]
public string Name { get; set; }
public bool ShouldSerializeId()
{
return DataType == DataTypes.Id;
}
public bool ShouldSerializeCategoryId()
{
return DataType == DataTypes.CategoryId;
}
}
private static MainCategories Deserialize(string json)
{
Dictionary<string, List < SubCategory >> jsonBody = new Dictionary<string, List<SubCategory>>();
JObject jObject = JObject.Parse(json);
// the outer object {one...two..}
foreach (KeyValuePair<string, JToken> jMainCategory in jObject)
{
// jMainCategory => "one": [{...}, {...}]
string key = jMainCategory.Key;
List<SubCategory> values = new List<SubCategory>();
foreach (JObject jSubCategory in jMainCategory.Value)
{
//jsubCategory => {"name" : ..., "ID": ... }
SubCategory subCategory = new SubCategory();
JToken idProperty;
if (jSubCategory.TryGetValue("ID", out idProperty))
{
subCategory.DataType = DataTypes.Id;
subCategory.Id = idProperty.Value<int>();
}
else
{
subCategory.DataType = DataTypes.CategoryId;
subCategory.Id = jSubCategory["categoryID"].Value<int>();
}
subCategory.Name = jSubCategory["name"].Value<string>();
subCategory.Parent = key;
// subCategory.AnotherProperty = jSubCategory["anotherproperty"].Value<type>();
values.Add(subCategory);
}
jsonBody.Add(key, values);
}
return jsonBody;
}
public static MainCategories WhereNameStartsWith(this MainCategories jsonBody, string str)
{
MainCategories result = new MainCategories();
//if you want to keep the result json structure `as is` return a MainCategories object
foreach (var subCategory in jsonBody.SelectMany(mainCategory => mainCategory.Value).Where(subCategory => subCategory.Name.StartsWith(str)))
{
if(result.ContainsKey(subCategory.Parent))
result[subCategory.Parent].Add(subCategory);
else
result.Add(subCategory.Parent, new List<SubCategory> {subCategory});
}
// if you just want the subcategories matching the condition create a WhereListNameStartsWith method
// where `result` is a list of subcategories matching the condition
return result;
}
foreach (var subCategory in jsonBody.SelectMany(mainCategory => mainCategory.Value).Where(subCategory => subCategory.DataType == DataTypes.CategoryId))
string jsonIn ="{\"One\":[{\"ID\":1,\"name\":\"s\"}," +
"{\"categoryID\":2,\"name\":\"c\"}]," +
"\"Two\":[{\"ID\":3,\"name\":\"l\"}]," +
"\"Three\":[{\"ID\":8,\"name\":\"s&P\"}," +
"{\"ID\":52,\"name\":\"BB\"}]}";
MainCategories desrializedJson = Deserialize(jsonIn);
MainCategories filtered = desrializedJson.WhereNameStartsWith("s");
string jsonOut = JsonConvert.SerializeObject(desrializedJson, Formatting.None);
Debug.Assert(jsonOut == jsonIn); //true
public enum DataTypes
{
Id,
CategoryId
};