2016-08-23 161 views
0

我只是嘗試反序列化一個Json數組,但它不起作用。 我可以在輸出框閱讀以下消息:在Newtonsoft中反序列化C#中的JSON數組

「Newtonsoft.Json.JsonReaderException:無效JavaScript屬性 標識符字符:」。路徑 '[0]',第2行,位置37」

我的代碼:

using System; 
using Android.App; 
using Android.Content; 
using Android.Runtime; 
using Android.Views; 
using Android.Widget; 
using Android.OS; 
using Newtonsoft; 
using System.Collections.Generic; 
using Newtonsoft.Json; 
using Newtonsoft.Json.Linq; 

namespace JsonTest 
{ 
    [Activity(Label = "JsonTest", MainLauncher = true, Icon = "@drawable/icon")] 
    public class MainActivity : Activity 
    { 

     protected override void OnCreate(Bundle bundle) 
     { 
      base.OnCreate(bundle); 

      // Set our view from the "main" layout resource 
      SetContentView(Resource.Layout.Main); 

      // Get our button from the layout resource, 
      // and attach an event to it 
      Button button = FindViewById<Button>(Resource.Id.MyButton); 

      button.Click += delegate 
      { 
       string json = @"[{ 
            id': '1', 
            'nom': 'zooz', 
            'prenom': 'Jack'         
           }, { 
            'id': '2', 
            'nom': 'toto', 
            'prenom': 'Blaireau'         
           }]"; 

       var a = JsonConvert.DeserializeObject<List<Person>>(json); 
       //JArray b = JArray.Parse(json); 


       Console.WriteLine(a); 
       // [email protected]}; 
      }; 
     } 

     public class Account 
     { 
      public string id { get; set; } 
      public string nom { get; set; } 
      public string prenom { get; set; } 
     } 

     public class Person 
     { 
      public Account person; 
     } 


    } 
} 

感謝你的幫助。

+1

單引號(「)似乎是失蹤‘身份證’:」 1' – hellowstone

+0

謝謝你。這是一個愚蠢的錯誤。 – Matthaousse

回答

2

單引號的ID丟失

string json = @"[{ 
        'id': '1', 
        'nom': 'zooz', 
        'prenom': 'Jack'         
        }, 
        { 
        'id': '2', 
        'nom': 'toto', 
        'prenom': 'Blaireau'         
        }]"; 

也模型Person必須是持有Account

public class Person 
    { 
     public List<Account> person; 
    } 
0

你的JSON缺少單引號名單,也相當於List<Account>而不是List<Person>。這應該JSON序列化成功進入名單

[{ 'person':{ 
    'id': '1', 
    'nom': 'zooz', 
    'prenom': 'Jack'         
}}, { 'person': { 
    'id': '2', 
    'nom': 'toto', 
    'prenom': 'Blaireau'         
}}] 
+0

這種情況下需要另一個模型類,其中包含人員列表 – Mostafiz

+0

該帳戶類具有像JSON一樣的id,nom和prenom屬性。 person類有一個名爲person的單個屬性,它是該帳戶類的一個實例。因此,要反序列化爲「List 」,您必須添加具有帳戶JSON結構的個人資產。其他選項是反序列化爲一個'List '。但是,根據我的所見,不需要另一個模型類... – rmc00

+0

那是真的,但是看看你的json的答案 – Mostafiz

相關問題