How to access nested object from JSON with Json.NET in C#

本小妞迷上赌 提交于 2019-12-06 10:11:47

问题


How can I select the json value "estimatedLocationDate" within a nested object using class decoration? The property "estimatedLocationDate" always returns null instead of the value 2015-10-01T14:00:00.000. The other decorated values return the proper values.

Here is my C# class

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

And This is the 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"
        },

回答1:


Your classes should look something like this (this is incomplete though):

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



回答2:


The JSON you posted is not valid. You can validate your JSON at JsonLint.

Let's assume below is your JSON data.

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

The easy way to read the whole JSON is to deserialize it to proper class hierarchy. If you do not have that already, you can create following these steps in Visual Studio

  • Copy your JSON data
  • Create a new empty class in VS
  • VS > Edit > Paste Special > Paste JSON As Classes

This are the generated classes

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

Now, it's easy to read the whole object and access your estimatedLocationDate like this

var jsonString = File.ReadAllText(@"C:\YourDirectory\YourFile.json");

PlanetRoot planet = JsonConvert.DeserializeObject<PlanetRoot>(jsonString);
DateTime estimatedLocationDate = planet.planet.First().product.estimatedLocationDate;

OR, if you do not want to read the whole object, you can directly read that property using Json.NET Linq-to-JSON like this

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



回答3:


Since product represents another object, you will need to create a class for it:

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;

Note that:

  • JSON you have posted is invalid. Let's suppose that you have copied not the whole JSON, and ignore this since "The other decorated values return the proper values."
  • It is better to give UpperCamelCase names to C# properties



回答4:


You could use an inner class for the Product, and expose it using a property like so.

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


来源:https://stackoverflow.com/questions/33886361/how-to-access-nested-object-from-json-with-json-net-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!