Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save ichiroku11/5254747 to your computer and use it in GitHub Desktop.
Json.NETでプロパティ名をCamel形式にしてシリアライズ(CamelCasePropertyNamesContractResolver)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace ConsoleApp {
class User {
public string FirstName { get; set; }
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,
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var json = JsonConvert.SerializeObject(user, settings);
Console.WriteLine(json);
// {
// "firstName": "悟空",
// "lastName": "孫"
// }
// デシリアライズ
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