Home > Enterprise >  Deserialize Json with class names that are not always the same, in C#
Deserialize Json with class names that are not always the same, in C#

Time:05-22

I'm trying to deserialize a response from a firebase realtime database get/json, to get user locations that are online

example response:

{
  "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
    }
  }
}

I put this into a json to c# class converter and it creates a class for each user (Test1, Test2, Test3, etc). This would work, if the users from the example are the only users to be in the response. If I had a sixth user named "6test", I would need to also create a class for that one too.

How can I use the Json converter (Newtonsoft.Json or System.Text.Json) to return a user in a list<User>

CodePudding user response:

you can use a dictionary in your case

using Newtosoft.Json;

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

classes

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; }
}

how to use

Test test5=tests["test5"];

or if you want to use list instead of Dictionary

var jsonParsed = JObject.Parse(json); 

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

how to use

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

class

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