2016-08-30 8 views
-1

以下のjson文字列をオブジェクトのリストに変換しようとしています。私はエラーが発生しています。あなたは助けてもらえますか?以下のjson文字列をC#のオブジェクトリストに変換する方法

string jsonp = @"{ 
    'data': [ { 'SectionId':1,'Name':'Bachelor ','NavigationRoute':'applicantExam/education','Position':15,IsEducation':true,'IsEducationCollegeDegree':null,'previousSection':null,'nextSection':null,'IsCurrent':null,'SectionCompleted':null}, 
      { 'SectionId':2,'Name':'Master','NavigationRoute':'applicantExam/education','Position':20,'IsEducation':true,'IsEducationCollegeDegree':null,'previousSection':null,'nextSection':null,'IsCurrent':null,'SectionCompleted':null} ] 
    }"; 

ExamSectionModel[] m = JsonConvert.DeserializeObject<ExamSectionModel[]>(jsonp); 
foreach(var x in m) 
{ 
    Console.WriteLine(x.Name); 
} 
+0

このリンクはあなたに役立つと思います: http://stackoverflow.com/questions/19581820/how-to-convert-json-array-to-list-of-objects-in-c-sharp –

答えて

0

試験セクションのデータ配列がJSONのルートレベルにありません。それはdataプロパティ内の1つ下のレベルです。修正するには、ラッパークラスを作成し、そのにデシリアライズする必要があります。

public class RootObject 
{ 
    public ExamSectionModel[] Data { get; set; } 
} 

public class ExamSectionModel 
{ 
    public int SectionId { get; set; } 
    public string Name { get; set; } 
    public string NavigationRoute { get; set; } 
    public int Position { get; set; } 
    public bool IsEducation { get; set; } 
    public bool? IsEducationCollegeDegree { get; set; } 
    public object previousSection { get; set; } 
    public object nextSection { get; set; } 
    public bool? IsCurrent { get; set; } 
    public bool? SectionCompleted { get; set; } 
} 

その後:

RootObject root = JsonConvert.DeserializeObject<RootObject>(jsonp); 
foreach(var x in root.Data) 
{ 
    Console.WriteLine(x.Name); 
} 

はフィドル:https://dotnetfiddle.net/TUFouk

さておき、あなたのJSONが欠けているように見えるとして最初の行には'Position':15,の後、IsEducation':trueの前に引用してください。私はそれが質問の誤植であると仮定していますが、そうでない場合は、JSONで修正する必要があります。そうしないと、解析が失敗します。

また、標準に準拠するには、一重引用符ではなく、JSONで技術的に二重引用符を使用する必要があります。 (JSON.orgを参照してください。)JSON.netは一重引用符を扱うことができますが、他のパーサーはあまり許されないかもしれません。

関連する問題