Gearbolt
Gearbolt

Reputation: 75

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

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

Upvotes: 3

Views: 12501

Answers (4)

Arghya C
Arghya C

Reputation: 10078

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>();

Upvotes: 10

Tyress
Tyress

Reputation: 3653

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

Upvotes: 0

sQuir3l
sQuir3l

Reputation: 1383

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

Upvotes: 0

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34244

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

Upvotes: 0

Related Questions