1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Json形式の文字列を自作クラスのListにする方法

Posted at

もっと単純な方法があるかもしれないけどとりあえずこんな感じです↓
※要「Newtonsoft.Json」参照

/// <summary>
/// 自作クラス
/// </summary>
public class MyClass
{
    public MyClass()
    { 
    }
    public MyClass(string name, string sex, string bType)
    {
        this.Name = name;
        this.Sex = sex;
        this.BloodType = bType;
    }
 
    public string Name { get; set; }
    public string Sex { get; set; }
    public string BloodType { get; set; }
}
 
/// <summary>
/// てすと
/// </summary>
public void test()
{
    List<MyClass> li = new List<MyClass>();
    li.Add(new MyClass("太郎", "M", "B"));
    li.Add(new MyClass("花小", "F", "A"));
    li.Add(new MyClass("あんぱん男", "M", "A"));
    li.Add(new MyClass("華麗犯男", "M", "B"));
    li.Add(new MyClass("努筋女", "F", "O"));
 
    // Json形式の文字列にする
    string json = JsonConvert.SerializeObject(li);
 
        List<MyClass> liD = new List<MyClass>();
 
    // Json形式の文字列をList型のコレクションに格納する
    liD = JsonConvert.DeserializeObject<List<MyClass>>(json);
}

Deserializeする際のクラスのメンバ名とJsonのメンバのプロパティ名が
一致していなければこの方法は使えないです。

逆に言うと一致させておけばこんな簡単にListにすることができるという感じです。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?