Created
March 27, 2013 14:37
-
-
Save ichiroku11/5254660 to your computer and use it in GitHub Desktop.
Json.NETでプロパティ名を変更してシリアライズ・デシリアライズ(JsonPropertyAttribute)
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.IO; | |
| using System.Linq; | |
| using System.Text; | |
| using Newtonsoft.Json; | |
| namespace ConsoleApp { | |
| class User { | |
| [JsonProperty("first_name")] | |
| public string FirstName { get; set; } | |
| [JsonProperty("last_name")] | |
| public string LastName { get; set; } | |
| public override string ToString() { | |
| return string.Format(@"{{ | |
| FirstName = ""{0}"", | |
| LastName = ""{1}"" | |
| }}", FirstName, LastName); | |
| } | |
| } | |
| class Program { | |
| static void Main(string[] args) { | |
| var user = new User { | |
| FirstName = "悟空", | |
| LastName = "孫" | |
| }; | |
| // シリアライズ | |
| var settings = new JsonSerializerSettings { | |
| Formatting = Formatting.Indented | |
| }; | |
| var json = JsonConvert.SerializeObject(user, settings); | |
| Console.WriteLine(json); | |
| // { | |
| // "first_name": "悟空", | |
| // "last_name": "孫" | |
| // } | |
| // デシリアライズ | |
| Console.WriteLine(JsonConvert.DeserializeObject<User>(json)); | |
| // { | |
| // FirstName = "悟空", | |
| // LastName = "孫" | |
| // } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment