c# - JSON 字符串到 C# 中的模型/HashMap/字典

标签 c# json dictionary hashmap

我有 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"
}
]
}

我想:

  1. 将此 JSON 带到任何对象(如 JObject)

  2. 根据不同的条件过滤 JSON(如名称以 s 开头等)

  3. 将此 JSON 返回给客户端

我尝试过的事情: 1. 创建模型:

class Model
{
public int Id;
public string name;
}
class MainModel
{
public string mainName;
public List<Model> categories;
}

并使用这些模型来:

List<MainModel> m = json_serializer.DeserializeObject(jsonString);
  1. 我也尝试过字典,但无法抛出异常。

如有任何帮助,我们将不胜感激。

最佳答案

以下将允许您将 JSON 反序列化为字典并对其进行过滤。这使用 Newtonsoft.Json Nuget 包,但这很常见。代码贴在下面。在这里找到工作示例 .Net Fiddle .

using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;


public class Program
{
    public static void Main()
    {
        var 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\"}]}";      
        var deserialized = JsonConvert.DeserializeObject<Dictionary<string, List<Model>>>(json);

        Console.WriteLine(deserialized["One"][0].name);

        Console.WriteLine("Filter to starts with s");
        var filtered = deserialized.SelectMany(item => item.Value).Where(innerItem => innerItem.name.StartsWith("s"));
        foreach(var item in filtered){
            Console.WriteLine(item.name);   
        }

    }

    public class Model{
        public int ID {get;set;}
        public string name {get;set;}
        public int categoryID {get;set;}
    }
}

关于c# - JSON 字符串到 C# 中的模型/HashMap/字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45580794/

相关文章:

ruby - 将 Hashie::Mash 输出解析为 ruby​​ 中的 Json

Python - 比较2个二维字典

c++ - 用户定义的类作为模板参数

c# - 如何在 jquery 中创建 JSON 字典数组?

c# - Google Cloud Storage api (c#) - 缓存 header 元数据

c# - 带枚举的 RegularExpression 属性

c# - 将字典扩展为 JSON 字段

asp.net-mvc - ASP.net MVC - 强类型对象来表示我传递给 View 的 Json 对象

C# foreach 内存缓存和字符串内存优化

json - 使用 int 键解码嵌套映射