C#でJsonを扱う Json.Net JToken/JObject/JArray編

C#でJsonを扱う DynamicJson編
C#でJsonを扱う Json.Net JToken/JObject/JArray編
C#でJsonを扱う Json.Net DeserializeObject編
・C#でJsonを扱う System.Text.Json編

Json.Netについて

Json.NET – Newtonsoft

App.xaml

<Application x:Class="WpfApp7.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp7"
             StartupUri="View\MainView.xaml">
    <Application.Resources>
         
    </Application.Resources>
</Application>

MainView.xaml

<Window x:Class="WpfApp7.View.MainView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
        xmlns:l="http://schemas.livet-mvvm.net/2011/wpf"
        xmlns:local="clr-namespace:WpfApp7.View"
        xmlns:vm="clr-namespace:WpfApp7.ViewModel"
        mc:Ignorable="d"
        Title="MainView" Height="450" Width="800">

    <Window.DataContext>
        <vm:MainViewModel/>
    </Window.DataContext>

    <i:Interaction.Triggers>
        <i:EventTrigger EventName ="ContentRendered">
            <l:LivetCallMethodAction MethodTarget="{Binding}" MethodName="OnContentRendered" />
        </i:EventTrigger>
    </i:Interaction.Triggers>

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="auto"/>
        </Grid.RowDefinitions>

        <Label Grid.Row="0" Grid.Column="0" Content="{Binding Title}"/>

        <ListView Grid.Row="1" Grid.Column="0" ItemsSource="{Binding arrayForecasts}">
            <ListView.Style>
                <Style TargetType="ListView">
                    <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Visible"/>
                    <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Hidden"/>
                </Style>
            </ListView.Style>
            <ListView.ItemsPanel>
                <ItemsPanelTemplate>
                    <VirtualizingStackPanel Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </ListView.ItemsPanel>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <Label Content="{Binding Date}"/>
                        <Image Source="{Binding ImageURL}"/>
                        <Label Content="{Binding Telop}"/>
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

        <Label Grid.Row="2" Grid.Column="0" Content="{Binding Description}"/>
    </Grid>
</Window>

MainViewModel.cs

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace WpfApp7.ViewModel
{
    public class MainViewModel : Livet.ViewModel
    {
        public class clsForecasts
        {
            public string Date { get; set; } = "";
            public string ImageURL { get; set; } = "";
            public string Telop { get; set; } = "";
        }

        private string _Title = "";
        public string Title
        {
            get
            {
                return _Title;
            }
            set
            {
                _Title = value;
                RaisePropertyChanged();
            }
        }

        private string _Description = "";
        public string Description
        {
            get
            {
                return _Description;
            }
            set
            {
                _Description = value;
                RaisePropertyChanged();
            }
        }

        private ObservableCollection<clsForecasts> _arrayForecasts = new ObservableCollection<clsForecasts>();
        public ObservableCollection<clsForecasts> arrayForecasts
        {
            get
            {
                return _arrayForecasts;
            }
            set
            {
                _arrayForecasts = value;
                RaisePropertyChanged();
            }
        }

        public void OnContentRendered()
        {
            string strSource = "";

            using (System.Net.WebClient objWebClient = new System.Net.WebClient())
            {
                // JSONデータの取得
                strSource = objWebClient.DownloadString("http://weather.livedoor.com/forecast/webservice/json/v1?city=130010");
            }

            // Unicodeエスケープ文字を元に戻す
            strSource = Regex.Unescape(strSource);

            // JTokenに変換 下記3つの手法どれでもよい
            JToken objJToken = JToken.Parse(strSource);
            //JToken objJToken = JsonConvert.DeserializeObject<JToken>(strSource);
            //JToken objJToken = (JToken)JsonConvert.DeserializeObject(strSource);

            // 値の取り出し方① JTokenからいきなり
            Title = objJToken["title"].ToString();

            // 値の取り出し方② オブジェクトであるJObjectに変換してから取得
            Description = (objJToken is JObject) ? ((JObject)objJToken)["description"]["text"].ToString() : "";

            // 配列か否かは、JArray型か否かで判定
            if (((JObject)objJToken)["forecasts"] is JArray)
            {
                foreach(JObject objForecast in ((JObject)objJToken)["forecasts"])
                {
                    arrayForecasts.Add(
                        new clsForecasts() {
                            Date = objForecast["date"].ToString(),
                            ImageURL = objForecast["image"]["url"].ToString(),
                            Telop = objForecast["telop"].ToString()
                        }
                    );
                }
            }

        }
    }
}

C#, WPFJson, Json.net

Posted by とど