解析具有不确定数据的json

时间:2016-09-05 12:50:42

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

如何解析具有Assets对象的json未知?

作为

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

3 个答案:

答案 0 :(得分:5)

如果您确定Assets只是一堆具有不同类型值的键,那么您可以使用IDictionary<string, object>来存储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);

答案 1 :(得分:2)

您可以将dynamic用作Assets类型:

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

然后

RootObject ro = JsonConvert.DeserializeObject<RootObject>(json);

答案 2 :(得分:0)

如果您只是想在不创建自定义C#对象的情况下解析JSON,则可以使用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"]);

您将需要可以从NuGet安装的Newtonsoft.Json。