0

How to parse json that have the Assets object is unknown?

As

{   
    "ClassName": "Excel",
    "Teacher": "Esther",
    "Student": 50,
    "Aircond": 0,
    "Assets": {
        "Chair": 50,
        "Table": 50,
        "Fan": 2,
        and might be more here and is unknown to me
    }
}
superhuman1314
  • 242
  • 2
  • 11

3 Answers3

5

If you know for sure that the Assets are just a bunch of keys with different kind of values, then you can use an IDictionary<string, object> to store the Assets:

public class MyClass
{
    public string ClassName { get; set; }
    public string Teacher { get; set; }
    public int Student { get; set; }
    public int Aircond { get; set; }
    public IDictionary<string, object> Assets { get; set; }
}

var myClass = JsonConvert.DeserializeObject<MyClass>(json);
fknx
  • 1,775
  • 13
  • 19
2

You can use dynamic as Assets type:

public class RootObject
{
    public string ClassName { get; set; }
    public string Teacher { get; set; }
    public int Student { get; set; }
    public int Aircond { get; set; }
    public dynamic Assets { get; set; }
}

And then

RootObject ro = JsonConvert.DeserializeObject<RootObject>(json);
BWA
  • 5,672
  • 7
  • 34
  • 45
0

If you just want to parse the JSON without creating a custom C# object, you could use JObject.Parse.

string json = "{\n\t\"ClassName\": \"Excel\",\n\t\"Teacher\": \"Esther\",\n\t\"Student\": 50,\n\t\"Aircond\": 0,\n\t\"Assets\": {\n\t\t\"Chair\": 50,\n\t\t\"Table\": 50,\n\t\t\"Fan\": 2,\n\t\t\"More\": \"randomText\"\n\t}\n}";
var jObject = JObject.Parse(json);
Console.WriteLine(jObject["Assets"]["More"]);

You will require Newtonsoft.Json which you can install from NuGet.