심재운 블로그

반응형

JSON object 를 C# object 로 변환하기

 

 

https://stackoverflow.com/a/28061832

 

How to Convert JSON object to Custom C# object?

Is there an easy way to populate my C# Object with the JSON object passed via AJAX? This is the JSON Object passed to C# WEBMETHOD from the page using JSON.stringify { "user": { ...

stackoverflow.com

public class User
{
    public User(string json)
    {
        JObject jObject = JObject.Parse(json);
        JToken jUser = jObject["user"];
        name = (string) jUser["name"];
        teamname = (string) jUser["teamname"];
        email = (string) jUser["email"];
        players = jUser["players"].ToArray();
    }

    public string name { get; set; }
    public string teamname { get; set; }
    public string email { get; set; }
    public Array players { get; set; }
}

// Use
private void Run()
{
    string json = @"{""user"":{""name"":""asdf"",""teamname"":""b"",""email"":""c"",""players"":[""1"",""2""]}}";
    User user = new User(json);

    Console.WriteLine("Name : " + user.name);
    Console.WriteLine("Teamname : " + user.teamname);
    Console.WriteLine("Email : " + user.email);
    Console.WriteLine("Players:");

    foreach (var player in user.players)
        Console.WriteLine(player);
 }

 

 

Newtonsoft.Json.JsonConvert.DeserializeObject() 활용하여 간략하게 한 줄 표현으로도 가능 합니다.

Mycustomclassname oMycustomclassname = Newtonsoft.Json.JsonConvert.DeserializeObject<Mycustomclassname>(jsonString);

 

Model 이 없을 경우 dynamic 키워드를 사용해도 됩니다.

var oMycustomclassname = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(jsonString);
반응형

댓글

비밀글모드