C#/JSON: Newtonsoft.Json ã®æãç°¡åãªä½¿ãæ¹
C#er ã«ã¯æ¨æºã©ã¤ãã©ãªã¼ã«æºãã¦ã馴æã¿ããã JSON ãæ±ãã©ã¤ãã©ãªã¼ Newtonsoft.Json
ãããããã ããããããããã£ã¦ã¯ãªãã ããããªè§£èª¬ãç¡ãï¼å人ã®ææ³ã§ããï¼ã®ã§ç§ã使ãã«ãããæä½é調æ»ããã¡ã¢ãæ®ãã
使ç¨ãã主ãªåå空éã¯2ã¤ãLinq
ã using
ããªãã¨ä¸è¦ LINQ
çã«ã¯ä½¿ããªãå ´åã«ãé¢åãèµ·ãããå
·ä½çã«ã¯ãã®ãã¨ããã«å®è£
ä¾ã«ä½¿ã JToken
ã Linq
åå空éã«æå±ãã¦ããã
using Newtonsoft.Json; using Newtonsoft.Json.Linq;
ããããã©ã¤ãã©ãªã¼ã®å
·ä½çãªä½¿ç¨ä¾ã¯ä¸»ã«ã¯æ§é åããããã¼ã¿ã® JSON
åã¨è¨èªãã¤ãã£ããã¼ã¿æ§é ã¸ã®æ»ãã ãããNewtonsoft.Json
ã C#
ã§ä½¿ãå ´åããã¯é常ã«ç°¡åã«å®è£
ã§ããã
class MyDataType { public int Nyanko { get; set; } public string Wanko { get; set; } } void Experiment() { // è¨èªãã¤ãã£ããªã¦ã¼ã¶ã¼å®ç¾©å -> JSON ãªãã¸ã§ã¯ã var data = new MyDataType() { Nyanko = 123, Wanko = "woowoo" }; var json_object = JToken.FromObject( data ); // JSON ãªãã¸ã§ã¯ã -> JSON æåå var json_string = json_object.ToString(); // JSON æåå -> è¨èªãã¤ãã£ããªã¦ã¼ã¶ã¼å®ç¾©å var data2 = JsonConvert.DeserializeObject< MyDataType >( json_string ); }
åãã©ãã§æååã«ããã¨ã©ãã§ãããããäºã¯ãããã¬ã¼ãã¤ã³ããªã»ã³ã¹ã§è¦ãã°è¯ãäºãªã®ã§ãã®ã¡ã¢ã§ã¯è§£èª¬ãçãã
ãã®æ¹æ³ã®åªç§ãªç¹ã¨ãã¦ã
- ã¦ã¼ã¶ã¼å®ç¾©åããã®ããããã£ã¼ã«ç¹å¥ãªå±æ§ã追å ããå¿ è¦ã¯ç¡ãäºãï¼å¨ç¨ãªäºããããããã°å°ç¨ã®å±æ§ã追å ããæ¹æ³ãããï¼
JToken.FromObject
/JsonConvert.DeserializeObject< T >
ã¯IEnumerable
ãDictionary
ãèªåçã«æ±ã£ã¦ãããäºã
ãæããããã
ä¾ãã°ã WPF
ã® ListView
ã³ã³ããã¼ã«ã®ãã¼ã¿ã®å®ä½ã¨ãã¦ãã°ãã°æ±ãäºã«ãªã System.Collections.ObjectModel
åå空éã® ObservableCollection
åãããããããã®æ±ããç¹å¥ã«æ°ã«ããå¿
è¦ç¡ã Newtonsoft.Json
㯠JSON ã¨ã®ç¸äºå¤æãè¡ã£ã¦ãããã
var data = new ObservableCollection< MyDataType >(); data.Add( new MyDataType() { Nyanko = 1, Wanko = "wanwan" } ); data.Add( new MyDataType() { Nyanko = 3, Wanko = "qwwwn" } ); var json_object = JToken.FromObject( data ); Console.WriteLine( json_object );
ãã®ãããªå¿ç¨ã®å ´åã«ãç¹å¥ãªäºã¯ä¸è¦ã§ JSON åã§ããã以ä¸ã¯ãã®çµæå¾ããã JSON:
[ { "Nyanko": 1, "Wanko": "wanwan" }, { "Nyanko": 3, "Wanko": "qwwwn" } ]
C# ãã¤ãã£ãã®ãªãã¸ã§ã¯ãã¸æ»ãå ´åãç¹å¥ãªäºã¯ä¸è¦:
// æ¢ã«ãã ObservableCollection< MyDataType > ã®ãªãã¸ã§ã¯ãã¸ç´æ¥æ»ãã data.Clear(); data = JsonConvert.DeserializeObject< ObservableCollection< MyDataType >>( json_object.ToString() ); foreach ( var datum in data ) Console.WriteLine( "N={0} W={1}", datum.Nyanko, datum.Wanko );
N=1 W=wanwan N=3 W=qwwwn
ããã¸ã便å©ð
大éæã«ã¯ããã ãã§ååã«ä½¿ããã JValue
JObject
JArray
ã®åºæ¬çãªæ§æã¨åãæ±ããã©ã¤ãã©ãªã¼ã®å
¨è²ã詳細ã«ã¤ãã¦ã¯
ãªã©çºããã¨ããã
ããã¸ãæåãªã©ã¤ãã©ãªã¼ãããã®ã§ã°ã°ã£ã¦è§£èª¬è¨äºã§ãè¦ãã»ããæ©ãã ããã¨ç§ã使ãå§ãã«æã£ãã®ã ãã©ãã©ããã¤ã³ãããªè§£èª¬ãããã£ã¦ããªã解説ãä¸ä½ã«ä¸¦ã³æéãç¡é§ã«ãããä»åã¡ã¢ã«æ®ãã大éæãªä½¿ãæ¹ã¨å ¬å¼ API Reference ããªãããã®ãããã