I have a JSON file with the following structure:
{
"name": "ML4 093 Historical",
"unit": "pounds",
"data":[
{
"date": "1985-12-01",
"value": "250"
},
{
"date": "1985-11-01",
"value": "237"
},
{
"date": "1985-10-01",
"value": "286"
}
]
}
Long story short, I need to get the value that corresponds to a specific date (for example, 250 for 1985-12-01 or 237 for 1985-11-01).
I understand how to get the information for a single element (for example, getting pounds for unit), but I have no clue how to go about doing it in this case.
This is what I have to get the information for a single element:
using System.Text.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Label unitname = label3;
string QUERY_URL = "JSON URL HERE";
Uri queryUri = new Uri(QUERY_URL);
using (System.Net.WebClient client = new System.Net.WebClient())
{
var json_data = client.DownloadString(queryUri);
var jsonDocument = JsonDocument.Parse(json_data);
var rootElement = jsonDocument.RootElement;
var unitElement = rootElement.GetProperty("unit");
var unit = unitElement.GetString();
unitname.Text = unit;
}
}
}
}
JSON URL HERE is, obviously, replaced with the actual URL in the code – I just can’t share it publicly.
2
Answers
You can create a class representing this JSON object (keeping in mind that Data should be an entirely separate object, inside the parent object), like so:
Then to retrieve the value, an example would be:
You can create a model class
DataModel.cs
After that just a little modification in you code should work