-2

I am trying to read my nested JSON result and I'm able to read the data from the first array. But not able to read from the remaining.

BELOW IS THE CODE WHICH GIVES THE RESULT FROM THE ORDER NODE

Fiddle: https://dotnetfiddle.net/biXBqd

using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Collections;
using Newtonsoft.Json.Linq;
                
public class Program
{
public static void Main()
{
    string json = @"{""orders"": [
    {
        ""orderNumber"": ""12345"",
        ""orderDate"": ""2022-03-16"",
        ""status"": ""Completed"",
        ""state"": ""Completed"",
        ""description"": """",
        ""subs"": [
            {
                ""subsNumber"": ""54321"",
                ""Managed"": null,
                ""customFields"": {},
                ""FirstVersion"": null,
                ""LastVersion"": 1,
                ""Actions"": [
                    {
                        ""id"": ""abc"",
                        ""sequence"": 0,
                        ""TDates"": [
                            {
                                ""Date"": ""2022-03-16""
                            },
                            {
                                ""Date"": ""2022-03-16""
                            },
                            {
                                ""Date"": ""2022-03-16""
                            }
                        ]
                    }
                ]
            }
        ],
        ""customFields"": {
            ""OrderDelivery"": null,
            ""DateOrderDelivered"": null
        }
    }
],
""nextPage"": ""/orders?page=4"",
""success"": true
}";
    ArrayList profileAry1 = new ArrayList();
    JObject jsonparsing1 = JObject.Parse(json);
    JObject jsonparsing = JObject.Parse(json);
    var token = (JArray)jsonparsing.SelectToken("orders");
    List<string> AuthorList = new List<string>();
    
    foreach (orders orders in JsonConvert.DeserializeObject<List<orders>>(token.ToString()))
                {
                    string orderNumber = orders.orderNumber.ToString();
                    string orderDate = orders.orderDate.ToString();
                    string status = orders.status.ToString();
                    string state = orders.state.ToString();
                    string description = orders.description.ToString();
        
                    Console.WriteLine("Order Number: " + orderNumber);
                    Console.WriteLine("Order Number: " + orderDate);
                    Console.WriteLine("status: " + status);
                    Console.WriteLine("status: " + state);
                    Console.WriteLine("description: " + description);
                    Console.WriteLine();
    }
    PocoCourse items = JsonConvert.DeserializeObject<PocoCourse>(json);
    
    Console.WriteLine("success: " + items.Success);
    Console.WriteLine("Message: " + items.nextPage);    
    //Console.WriteLine("Number of Types: " + items.orders.Count);
}
}
public class PocoCourse
{
public bool Success { get; set; }
public string nextPage { get; set; }
public List<orders> orders { get; set; }
}
public class orders
{
public string orderNumber { get; set; }
public DateTime orderDate { get; set; }
public string status { get; set; }
public string state { get; set; }
public string description { get; set; }
public List<subs> subs { get; set; }

}
public class subs
{
[JsonProperty("subs")]
public string subsNumber { get; set; }
public string Managed { get; set; }
public string FirstVersion { get; set; }
public string LastVersion { get; set; }
//public List<subscriptions1> subscriptions { get; set; }
public List<List<object>> Points { get; set; }
}

I want to get the values from subs,Actions and TDates as well which I'm not able to achive.

Can anyone please help on this?

Sreepu
  • 123
  • 1
  • 1
  • 14
  • I'm not sure what the problem is. Have you tried with `orders.subs` inside your for loop? You can read that value. – Balastrong Mar 16 '22 at 18:12
  • Yes, but it didn't work. I have added the fiddle link above which has the code, which I have written. – Sreepu Mar 16 '22 at 18:20
  • I can access `orders.subs` in your fiddle and read its values – Balastrong Mar 16 '22 at 18:21
  • I'm new to coding, I think I'm missing something. Could you please share that part of code with me? So that I will understand how to access orders.subs. – Sreepu Mar 16 '22 at 18:23
  • @Balastrong I have tried again, still not understanding how to read the values from orders.subs. – Sreepu Mar 16 '22 at 18:32
  • 2
    What exactly is your problem? Are you asking *How to loop through `orders.subs`*? If so see here: https://dotnetfiddle.net/IOBGZV. As an aside, you need to remove `[JsonProperty("subs")]` from `public string subsNumber { get; set; }`. But your data model `subs` doesn't really match the JSON shown, is that your real problem? If so see [How to auto-generate a C# class file from a JSON string](https://stackoverflow.com/q/21611674/3744182) for tools to auto-generate a better model. – dbc Mar 16 '22 at 18:43
  • I was asking how to loop through orders.subs and it is working as expected now. Thank you so much for your help. – Sreepu Mar 16 '22 at 19:04

1 Answers1

2

you can use this code to get list of dates for example

Data data=JsonConvert.DeserializeObject<Data>(json); 

List<DateTime> dates = data.Orders[0].Subs[0].Actions[0].Dates.Select(d => d.Date ).ToList();

result

    2022-03-16
    2022-03-16
    2022-03-16

or actions

List<Action> actions = data.Orders[0].Subs[0].Actions.ToList(); 

//or since you have only one

Action action = data.Orders[0].Subs[0].Actions.FirstOrDefault(); 

result

[
  {
    "id": "abc",
    "sequence": 0,
    "TDates": [
      {
        "Date": "2022-03-16T00:00:00"
      },
      {
        "Date": "2022-03-16T00:00:00"
      },
      {
        "Date": "2022-03-16T00:00:00"
      }
    ]
  }
]

or if you need only selected values you can do it without creating any classes. For example you can get list of dates

var jsonParsed= JObject.Parse(json);

List<DateTime> dates = jsonParsed["orders"][0]["subs"][0]["Actions"][0]["TDates"]
.Select(d => (DateTime) d["Date"]).ToList();

classes

    public partial class Data
    {
        [JsonProperty("orders")]
        public List<Order> Orders { get; set; }

        [JsonProperty("nextPage")]
        public string NextPage { get; set; }

        [JsonProperty("success")]
        public bool Success { get; set; }
    }

    public partial class Order
    {
        [JsonProperty("orderNumber")]
        public long OrderNumber { get; set; }

        [JsonProperty("orderDate")]
        public DateTimeOffset OrderDate { get; set; }

        [JsonProperty("status")]
        public string Status { get; set; }

        [JsonProperty("state")]
        public string State { get; set; }

        [JsonProperty("description")]
        public string Description { get; set; }

        [JsonProperty("subs")]
        public List<Sub> Subs { get; set; }

        [JsonProperty("customFields")]
        public OrderCustomFields CustomFields { get; set; }
    }

    public partial class OrderCustomFields
    {
        [JsonProperty("OrderDelivery")]
        public object OrderDelivery { get; set; }

        [JsonProperty("DateOrderDelivered")]
        public object DateOrderDelivered { get; set; }
    }

    public partial class Sub
    {
        [JsonProperty("subsNumber")]
        public long SubsNumber { get; set; }

        [JsonProperty("Managed")]
        public object Managed { get; set; }

        [JsonProperty("customFields")]
        public SubCustomFields CustomFields { get; set; }

        [JsonProperty("FirstVersion")]
        public object FirstVersion { get; set; }

        [JsonProperty("LastVersion")]
        public long LastVersion { get; set; }

        [JsonProperty("Actions")]
        public List<Action> Actions { get; set; }
    }

    public partial class Action
    {
        [JsonProperty("id")]
        public string Id { get; set; }

        [JsonProperty("sequence")]
        public long Sequence { get; set; }

        [JsonProperty("TDates")]
        public List<TDate> Dates { get; set; }
    }

    public partial class TDate
    {
        [JsonProperty("Date")]
        public DateTime Date { get; set; }
    }

    public partial class SubCustomFields
    {
    }
Serge
  • 40,935
  • 4
  • 18
  • 45