2014-09-20 16 views
8

Używam Newtonsoft JSON do serializowania/deserializacji moich obiektów. Jedna z nich zawiera tablicę z chronionym ustawiaczem, ponieważ konstruktor buduje samą tablicę i manipuluje tylko elementami.JSON deserialize to built protected setter array

To może być serializowane bez problemu, ale jeśli chodzi o deserializację, właściwość jest ignorowana, ponieważ nie jest publiczna. Próbowałem niestandardowego konwertera, ponieważ nie jest również wywoływany, ponieważ nie jest publiczny.

To jest zminimalizowane przykład:

public static class TestCoordsDeserialization 
{ 
    private class Coords 
    { 
     public Double X { get; set; } 
     public Double Y { get; set; } 
     public Double Z { get; set; } 
     public Double A { get; set; } 
    } 

    private class Engine 
    { 
     public string Text { get; set; } 
     public int Id { get; set; } 
     public Coords[] Outs { get; protected set; } 

     public Engine() 
     { 
      this.Outs = new Coords[3]; 
      for (int i = 0; i < this.Outs.Length; i++) 
      { 
       this.Outs[i] = new Coords(); 
      } 
     } 
    } 

    public static void Test() 
    { 
     Engine e = new Engine(); 
     e.Id = 42; 
     e.Text = "MyText"; 
     e.Outs[0] = new Coords() { A = 0, X = 10, Y = 11, Z = 0 }; 
     e.Outs[1] = new Coords() { A = 0, X = 20, Y = 22, Z = 0 }; 
     e.Outs[2] = new Coords() { A = 0, X = 30, Y = 33, Z = 0 }; 
     string json = JsonConvert.SerializeObject(e); 
     Console.WriteLine(json); //{"Text":"MyText","Id":42,"Positions":{"Test":9,"Outs":[{"X":10.0,"Y":11.0,"Z":0.0,"A":0.0},{"X":20.0,"Y":22.0,"Z":0.0,"A":0.0},{"X":30.0,"Y":33.0,"Z":0.0,"A":0.0}]}} 
     Engine r = JsonConvert.DeserializeObject<Engine>(json); 
     double value = r.Outs[1].X; // should be '20.0' 
     Console.WriteLine(value); 
     Debugger.Break(); 
    } 
} 

Jak mogę dokonać value być 20,0?

+1

kilka pomysłów tutaj: http://dotbrand.wordpress.com/2010/07/05/entities-with-privateprotected-setters-in-ravendb/ – dbc

Odpowiedz

14

Mark Outs z atrybutem [JsonProperty]:

private class Engine 
    { 
     public string Text { get; set; } 
     public int Id { get; set; } 
     [JsonProperty] // Causes the protected setter to be called on deserialization. 
     public Coords[] Outs { get; protected set; } 

     public Engine() 
     { 
      this.Outs = new Coords[3]; 
      for (int i = 0; i < this.Outs.Length; i++) 
      { 
       this.Outs[i] = new Coords(); 
      } 
     } 
    } 
+0

Niewiarygodne łatwe! Zwróciłem moją uwagę w dokumentach ... – ZoolWay