【问题标题】:Deserialize Json with class names that are not always the same, in C#在 C# 中使用不总是相同的类名反序列化 Json
【发布时间】:2022-06-11 00:51:28
【问题描述】:

我正在尝试反序列化来自 firebase 实时数据库 get/json 的响应,以获取在线的用户位置

示例响应:

{
  "test1": {
    "id": "test-1",
    "location": {
      "lat": 37.33097983,
      "long": -122.03063943
    }
  },
  "test2": {
    "id": "test-2",
    "location": {
      "lat": 37.33021864,
      "long": -122.02370753
    }
  },
  "test3": {
    "id": "test-3",
    "location": {
      "lat": 37.32873847,
      "long": -122.01980584
    }
  },
  "test4": {
    "id": "test-4",
    "location": {
      "lat": 37.32563464,
      "long": -122.01972943
    }
  },
  "test5": {
    "id": "test-5",
    "location": {
      "lat": 37.32472734,
      "long": -122.02127163
    }
  }
}

我将它放入一个 json 到 c# 类转换器,它为每个用户(Test1、Test2、Test3 等)创建一个类。如果示例中的用户是响应中唯一的用户,这将起作用。如果我有第六个用户名为“6test”,我还需要为那个用户创建一个类。

如何使用 Json 转换器(Newtonsoft.Json 或 System.Text.Json)在 list<User> 中返回用户

【问题讨论】:

    标签: c# json .net-core json.net


    【解决方案1】:

    你可以在你的情况下使用字典

    using Newtosoft.Json;
    
    Dictionary<string,Test> tests = JsonConvert.DeserializeObject<Dictionary<string,Test>>(json);
    

    public class Location
    {
        public double lat { get; set; }
        public double @long { get; set; }
    }
    
    public class Test
    {
        public string id { get; set; }
        public Location location { get; set; }
    }
    

    如何使用

    Test test5=tests["test5"];
    

    或者如果你想使用列表而不是字典

    var jsonParsed = JObject.Parse(json); 
    
    List<ListTest> list = jsonParsed.Properties().Select(p => new ListTest { Name = p.Name, Test = p.Value.ToObject<Test>() }).ToList();
    

    如何使用

    Test test4 = list.Where(f=>f.Name=="test4").Select(t=>t.Test).FirstOrDefault();
    

    public class ListTest
    {
        public string Name { get; set; }
        public Test Test { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多