Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8899

C#(csc.exe) - JSON読み込んでみた(シリアライズじゃないほう) - Windows10

$
0
0

経緯

JSONのフォーマットとなるクラスが事前に固定されていれば、DataContractJsonSerializerが使えるのだが、VSCodeのスニペットなど、変動的なケースがあり、もっと汎用的なやりかたを探した。

参考サイト

Windows.Data.Jsonが使えるらしい。UWPやらWinRTやら最近の流れについていけてない感がある。。

コンパイル用バッチ

コンパイル通すまでが最難関だった。
https://qiita.com/kob58im/items/3dc69c2e243528f275b6でやったのと同じのでよいということにさっき気づいた。

csc /r:C:\Windows\Microsoft.NET\assembly\GAC_MSIL\System.Runtime.WindowsRuntime\v4.0_4.0.0.0__b77a5c561934e089\system.runtime.windowsruntime.dll ^
/r:C:\Windows\Microsoft.NET\assembly\GAC_MSIL\System.Runtime.InteropServices.WindowsRuntime\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Runtime.InteropServices.WindowsRuntime.dll ^
/r:C:\Windows\Microsoft.NET\assembly\GAC_MSIL\System.Runtime\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Runtime.dll ^
"/r:C:\Program Files (x86)\Windows Kits\8.1\References\CommonConfiguration\Neutral\Annotated\Windows.winmd" %*

ソースコード

Visual Studio Codeのスニペットを読み込むとっかかりとなるソースコード。
まだ断片。

usingSystem;usingWindows.Data.Json;classJsonTest{[STAThread]staticvoidMain(string[]args){strings="{\"body\":[\"foo\",\"bar\"],\"description\":\"piyo\",\"prefix\":\"hoge\"}";JsonObjectjo=JsonObject.Parse(s);// int n = jo.Count; // オブジェクトの数foreach(stringkeyinjo.Keys){JsonValuejv=jo.GetNamedValue(key);Console.WriteLine("------------");Console.WriteLine("Name: "+key);Console.WriteLine("ValueType: "+jv.ValueType.ToString());Console.Write("Value: ");switch(jv.ValueType){caseJsonValueType.String:Console.WriteLine(jv.GetString());break;caseJsonValueType.Number:Console.WriteLine(jv.GetNumber());break;caseJsonValueType.Array:JsonArrayja=jv.GetArray();Console.Write("Count of array: ");Console.WriteLine(ja.Count);// ja.Sizeはなぜかコンパイルできない。右記サイトは間違っているのか?多分C#とほかの言語で異なる気がする。 https://docs.microsoft.com/ja-jp/uwp/api/windows.data.json.jsonarray.sizeforeach(JsonValuejvChildinja){if(jvChild.ValueType==JsonValueType.String){Console.WriteLine(jvChild.GetString());}}break;default:Console.WriteLine();break;}}}}

出力結果

------------
Name: body
ValueType: Array
Value: Count of array: 2
foo
bar
------------
Name: description
ValueType: String
Value: piyo
------------
Name: prefix
ValueType: String
Value: hoge

Viewing all articles
Browse latest Browse all 8899

Trending Articles