Skip to content

Instantly share code, notes, and snippets.

@ichiroku11
Created July 26, 2013 14:06
Show Gist options
  • Select an option

  • Save ichiroku11/6089130 to your computer and use it in GitHub Desktop.

Select an option

Save ichiroku11/6089130 to your computer and use it in GitHub Desktop.
JsonConvert.PopulateObject で、 デフォルト値が設定してあるインスタンスのプロパティを JSON から取得した値で上書き
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