2011-01-20 16 views
5

Czy ktoś może mi powiedzieć, jak mogę deserializować obiekt, który zawiera wiele atrybutów?Dodawanie wielu elementów w tablicy JSON do obiektu w języku C# przy użyciu Json.net

Biorąc pod uwagę scenariusz poniżej, kod działa poprawnie.

public ActionResult Index() 
{ 
    string json = @"{""name"": ""Person 2"",""email"": ""[email protected]""}"; 

    var emp = JsonConvert.DeserializeObject<Person>(json); 
    Response.Write(emp.name + emp.email); 
    return View(); 
} 

public class Person 
{ 
    public string name { get; set; } 
    public string email { get; set; } 
} 

Ale co mam zrobić, jeśli tablica zawiera wiele elementów, np

string json = @"{""data"": [{""name"": ""Person 1"",""email"": ""[email protected]""},{""name"": ""Person 2"",""email"": ""[email protected]""}]}"; 

góry dzięki

Odpowiedzi już podane poniżej były doskonałe dla problemu zapytałam, ale teraz poszedłem o krok do przodu. Czy ktoś może doradzić, co powinienem zrobić, gdyby json miał tablicę w nim np. dodanie adresu w?

{ 
    "data": [ 
     { 
      "name": "Person 1", 
      "email": "[email protected]", 
      "address": { 
       "address1": "my address 1", 
       "address2": "my address 2" 
      } 
     }, 
     { 
      "name": "Person 2", 
      "email": "[email protected]", 
      "address": { 
       "address1": "my address 1", 
       "address2": "my address 2" 
      } 
     } 
    ] 
} 
+0

Jeśli twoja klasa "Osoby" została również rozszerzona o właściwość klasy "Adres", to nie powinieneś robić nic. W przeciwnym razie mówisz, że tak nie jest i masz teraz tę "dodatkową" własność? – Enigmativity

Odpowiedz

5

Coś takiego nie pracował dla mnie w przeszłości:

JObject o = JObject.Parse(json); // This would be the string you defined above 
// The next line should yield a List<> of Person objects... 
List<Person> list = JsonConvert.DeserializeObject<List<Person>>(o["data"].ToString()); 

może chcesz ozdobić swój obiekt Person następująco:

[JsonObject(MemberSerialization.OptIn)] 
public class Person 
{ 
    [JsonProperty] 
    public string name{get;set;} 
    [JsonProperty] 
    public string email{get;set;} 
} 
1

Cofnięcie jak:

public class JsonData 
{ 
    public List<Person> Data {get;set;} 
} 
2

Możesz użyć typ anonimowy.

var template = new { data = new Person[] { } }; 
Person[] emps = JsonConvert 
    .DeserializeAnonymousType(json, template) 
    .data; 
Powiązane problemy