skip to Main Content

I receive a Json file. Now the other company change the Json and I have to find the right format for my class in C.Net and I’m not able to do so.

My Json looks like :
{

 {"xxx": [
 "d6952cb5c",
 "8587d4",
 "96b4d",
 "622201a",
 "55e0d455"
 ],
 "yyy": [
 "28f054091d"
 ],
 "zzz": []
}  

The thing is, I don’t know the name of the field I’m going to receive. So I’m not able to create a class with the correct field replacing xxx, yyy and zzz. I can receive more than 300 of these.

Normally I had create my class like this :

 public class Root
 {
    public List<string> xxx { get; set; }
    public List<string> yyy { get; set; }
    public List<object> zzz { get; set; }
 }

Someone has an idea on How I can create the right class, Or any other way to have my data in an object or a dictionary to read them separately ?

thanks

2

Answers


  1. Chosen as BEST ANSWER

    Finally working on my side, with some other solutions, I found somethig that works. Here's the code help with another stack overflow.

                dynamic parsed = JsonConvert.DeserializeObject(MyJSON);
                var jObj = (JObject)parsed;
    
                foreach (JToken token in jObj.Children())
                {
                    if (token is JProperty)
                    {
                        var prop = token as JProperty;
                        Console.WriteLine("hello {0}={1}", prop.Name, prop.Value);
                    }
                }
    

    Find the solution with another stackoverflow here: dynamic JContainer (JSON.NET) & Iterate over properties at runtime


  2. The easiest way for this specific example is to use Dictionary<string, string[]> to deserialize object:

    string json = """
    {
        "xxx": [
            "d6952cb5c",
            "8587d4",
            "96b4d",
            "622201a",
            "55e0d455"
        ],
        "yyy": [
            "28f054091d"
        ],
        "zzz": []
    }
    """;
    
    var document = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, string[]>>(json);
    foreach(string key in document.Keys)
    {
        Console.WriteLine(key);
        foreach (string value in document[key])
        {
            Console.WriteLine("t" + value);
        }
    }
    

    You will get this output:

    xxx
        d6952cb5c
        8587d4
        96b4d
        622201a
        55e0d455
    yyy
        28f054091d
    zzz
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search