Maya Wright
Maya Wright

Reputation: 77

How do I access only one part of JSON text in UWP C# app?

I am trying to create my first UWP C# app. When the button named 'Button' is clicked, JSON shows up within the text box named 'TextBox'.

I am trying to work out how I can access only one part of the JSON text (data.best_day.text) for example (in JavaScript) data.best_day.text would give 18 hrs 3 mins. I would like to do the same for this UWP app. I have read some resources but they didn't work or were way too complex to understand. Any help would be greatly appreciated. :)

picture of JSON that is shown when button is clicked

    // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
    
    namespace WakaTime
    {
        /// <summary>
        /// An empty page that can be used on its own or navigated to within a Frame.
        /// </summary>
        public sealed partial class MainPage : Page
        {
            public MainPage()
            {
                this.InitializeComponent();
            }
    
            private async void Button_Click(object sender, RoutedEventArgs e)
            {
                var client = new HttpClient();
                var text = await client.GetStringAsync("https://wakatime.com/share/@DontBugMie/bef7afe4-102d-47a9-9678-6335510ebedd.json");
              
                TextBox.Text = text;
            }
        }
    }

Upvotes: 0

Views: 217

Answers (2)

Roman Marusyk
Roman Marusyk

Reputation: 24619

If you are confident in the path, try this

using System.Text.Json;
...
var jsonDoc = JsonDocument.Parse(text);
var best_day = jsonDoc.RootElement.GetProperty("data").GetProperty("best_day").GetProperty("text").GetString();
TextBox.Text = best_day;

If you need more than one value, then it would be better to create a model (DTO) and deserialize to it

Upvotes: 1

ΩmegaMan
ΩmegaMan

Reputation: 31721

Get the actual JSON and go to a site which converts JSON to C# (Search for that). Also depending on the version Visual Studio, it may have the menu option of Edit - Paste Special - Paste JSON As CLasses which will also work. You will now have classes which you can add to your project which are based off of the JSON.

Then in your code deserialize to the model (or a list of the models). Once it is deserialized into an instance, access best_day as needed.


enter image description here

Upvotes: 0

Related Questions