Skip to content

Instantly share code, notes, and snippets.

@ichiroku11
Created March 27, 2013 14:37
Show Gist options
  • Select an option

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

Select an option

Save ichiroku11/5254660 to your computer and use it in GitHub Desktop.
Json.NETでプロパティ名を変更してシリアライズ・デシリアライズ(JsonPropertyAttribute)
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