如何在C#中使用JSON.NET从JSON访问嵌套对象

本文关键字:JSON NET 嵌套 对象 访问 | 更新日期: 2023-09-27 18:23:59

如何使用类装饰在嵌套对象中选择json值"estimatedLocationDate"?属性"estimatedLocationDate"始终返回null,而不是值2015-10-01T14:00:00.000。其他修饰的值返回正确的值。

这是我的C#

public string id { get; set; }
public string name { get; set; }
[JsonProperty("publishedDate")]
public string publishdate { get; set; }
[JsonProperty("estimatedLocationDate")]
public string estimatedLocationDate{ get; set; }
[JsonProperty("createdTime")]
public string createtime { get; set; }
[JsonProperty("lastUpdatedTime")]
public string lastupdate { get; set; }

这是JSON

"planet": [
    {
        "id": "123456",
        "planetid": "en-us/Jupiter-mars/---main",
        "name": "The planet Mercury",
        "description": "This is placeholder for the description",
        "publishedDate": "2013-10-14T23:30:00.000",
        "createtime": "2012-03-01T14:00:00.000",
        "product": {
            "moreid": "1427-48-bd-9-113",
            "color": "200",
            "imageUrl": "http://image.bing.com/Mercury.jpg",
            "neighbor": [
                {
                    "ring": "Two",
                    "moons": 2
                }
            ],
            "estimatedLocationDate": "2014-10-01T14:00:00.000"
        },

如何在C#中使用JSON.NET从JSON访问嵌套对象

您发布的JSON无效。您可以在JsonLint验证您的JSON

假设以下是您的JSON数据。

{ "planet": [
        {
            "id": "123456",
            "planetid": "en-us/Jupiter-mars/---main",
            "name": "The planet Mercury",
            "description": "This is placeholder for the description",
            "publishedDate": "2013-10-14T23:30:00.000",
            "createtime": "2012-03-01T14:00:00.000",
            "product": {
                "moreid": "1427-48-bd-9-113",
                "color": "200",
                "imageUrl": "http://image.bing.com/Mercury.jpg",
                "neighbor": [
                    {
                        "ring": "Two",
                        "moons": 2
                    }
                ],
                "estimatedLocationDate": "2014-10-01T14:00:00.000"
            }
        }
    ]
}

读取整个JSON的简单方法是将其deserialize到适当的类层次结构。如果您还没有,您可以在VisualStudio中创建以下步骤

  • 复制您的JSON数据
  • 在VS中创建一个新的空类
  • VS>编辑>特殊粘贴>将JSON粘贴为类

这是生成的类

public class PlanetRoot
{
    public Planet[] planet { get; set; }
}
public class Planet
{
    public string id { get; set; }
    public string planetid { get; set; }
    public string name { get; set; }
    public string description { get; set; }
    public Product product { get; set; }
    [JsonProperty("publishedDate")]
    public string publishdate { get; set; }
    [JsonProperty("createdTime")]
    public string createtime { get; set; }
}
public class Product
{
    public string moreid { get; set; }
    public string color { get; set; }
    public string imageUrl { get; set; }
    public Neighbor[] neighbor { get; set; }
    public DateTime estimatedLocationDate { get; set; }
}
public class Neighbor
{
    public string ring { get; set; }
    public int moons { get; set; }
}

现在,很容易读取整个对象并像一样访问estimatedLocationDate

var jsonString = File.ReadAllText(@"C:'YourDirectory'YourFile.json");
PlanetRoot planet = JsonConvert.DeserializeObject<PlanetRoot>(jsonString);
DateTime estimatedLocationDate = planet.planet.First().product.estimatedLocationDate;

或者,如果您不想读取整个对象,您可以使用Json.NETLinq直接读取该属性到JSON,就像这个

var jObject = JObject.Parse(jsonString);
var estLocDate = jObject["planet"][0]["product"]["estimatedLocationDate"].ToObject<DateTime>();

您的类应该是这样的(尽管这是不完整的):

class Planet
    {
        [JsonProperty("planet")]
        PlanetInfo[] planet { get; set; }
    }
    class Product
    {
        [JsonProperty("estimatedLocationDate")]
        string estimatedLocationDate {get;set;}
    }
    class PlanetInfo
    {
        public string id { get; set; }
        public string name { get; set; }
        [JsonProperty("publishedDate")]
        public string publishdate { get; set; }
        [JsonProperty("estimatedLaunchDate")]
        public string estimatedLaunchDate { get; set; }
        [JsonProperty("createdTime")]
        public string createtime { get; set; }
        [JsonProperty("lastUpdatedTime")]
        public string lastupdate { get; set; }
        [JsonProperty("product")]
        public Product product { get; set; }
    }

由于product代表另一个对象,您需要为它创建一个类:

public class Planet  
{
    public string id { get; set; }
    public string name { get; set; }
    [JsonProperty("publishedDate")]
    public string publishdate { get; set; }
    [JsonProperty("estimatedLaunchDate")]
    public string estimatedLaunchDate { get; set; }
    [JsonProperty("createdTime")]
    public string createtime { get; set; }
    [JsonProperty("lastUpdatedTime")]
    public string lastupdate { get; set; }
    public Product product { get; set; }
}
public class Product 
{
    public DateTime estimatedLocationDate { get; set; }
    /* Other members, if necessary */
}
string result = JsonConvert.DeserializeObject<Planet>(jsonString).product.estimatedLocationDate;

注意:

  • 您发布的JSON无效。让我们假设您没有复制整个JSON,并忽略这一点,因为"其他修饰的值返回正确的值。"
  • 最好为C#属性指定UpperCamelCase名称

您可以为Product使用内部类,并使用类似的属性来公开它。

public class JsonNet
{
    public static string jsonString = @"{ ""inner"" : { ""name"" : ""myname""}}";
    public static Test GetTest()
    {
        return JsonConvert.DeserializeObject<Test>(jsonString);
    }
}
public class Inner
{
    public string Name { get; set; }
}
public class Test
{
    public Inner Inner { get; set; }
    public string Name
    {
        get { return Inner.Name; }
        set { Inner.Name = value; }
    }
}