Created
July 26, 2013 14:06
-
-
Save ichiroku11/6089130 to your computer and use it in GitHub Desktop.
JsonConvert.PopulateObject で、
デフォルト値が設定してあるインスタンスのプロパティを JSON から取得した値で上書き
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| using System.Drawing; | |
| using System.Linq; | |
| using System.Text; | |
| using System.Threading.Tasks; | |
| using Newtonsoft.Json; | |
| namespace ConsoleApp { | |
| class Settings { | |
| public string FontName { get; set; } | |
| public int FontSize { get; set; } | |
| public bool LineNumbers { get; set; } | |
| } | |
| class Program { | |
| static void Main(string[] args) { | |
| // デフォルト値が設定してある | |
| var settings = new Settings { | |
| FontName = "Consolas", | |
| FontSize = 10, | |
| LineNumbers = true, | |
| }; | |
| // FontSize と LineNumbers が指定してある JSON を使って | |
| var json = @"{ 'FontSize': 12, 'LineNumbers': false }"; | |
| // settings.FontSize と settings.LineNumbers だけを上書きする | |
| JsonConvert.PopulateObject(json, settings); | |
| // よし | |
| Console.WriteLine(settings.FontName); // Consolas | |
| Console.WriteLine(settings.FontSize); // 12 | |
| Console.WriteLine(settings.LineNumbers); // false | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment