Search code examples
c#unity-game-enginejson.net

Parsing a JSON file with date format and add to list


I am parsing a JSON which has multiple dates but they are not ordered. I want to order them and add them to a list. Now this is the complicated part, I want to order them in descending order such as that :

2021-02-20
2021-02-19
2021-02-18
2021-02-17
2021-02-16
2021-02-15
2021-02-14
2021-02-13

I do not want to add all of them to my list, I only want to add for the past 7 days. So how do I do this?

The JSON format for the dates are:

"data": {
    "Days": [
      {
        "day": "2021-02-20"
      },
      {
        "day": "2021-02-17"
      },
      {
        "day": "2021-02-19"
      },
      {
        "day": "2021-02-15"
      },
      {
        "day": "2021-02-16"
      },
      {
        "day": "2021-02-18"
      },
      {
        "day": "2021-02-14"
      },
      {
        "day": "2021-02-13"
      },
      {
        "day": "2021-02-11"
      },
      {
        "day": "2021-02-12"
      }
   ]
  }

My Unity code where I am parsing it:

using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
using SimpleJSON;
using UnityEngine;

public List<string> Dates;

 void Start () {
        GetData();
    }

 public async void GetData() {
        
        UnityWebRequest request = await MyJSON.Post (JSONQuery);
        JSONNode itemsData = JSON.Parse (request.downloadHandler.text);
        var parseJSON = JSON.Parse (request.downloadHandler.text);
        Debug.Log ("DAYS: " + HttpHandler.FormatJson (request.downloadHandler.text)); //I am getting my parsed data here

        var Count = itemsData["data"]["Days"].Count;

        for(int i=0;i<Count ;i++)
        {
            Dates.Add(itemsData["data"]["Days"][i]["day"]);
        }

    }

Can I order the list based on descending order of the dates?


Solution

  • You can just do

    using System.Linq;
    
    ...
    
    Dates = Dates.OrderByDescending(x => x).Take(7).ToList();
    

    to get the ordered list with 7th first elements based on IComparable interface implemented by string, but you better to convert your dates into DateTime before that to order it in more appropriately form.

    var last7dateTimesDescending = Dates.Select(d => DateTime.ParseExact(d, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture).OrderByDescending(dt => dt.Ticks).Take(7).ToArray();