2017-08-28 50 views
0

在JSON.Net中,我可以將JSON文件讀入數據結構,然後僅將我感興趣的屬性轉換爲對象。舉例來說,如果我有一個像有沒有反序列化YAML文檔的特定屬性的方法?

{ 
    "Bob": { 
       "Steve": 5 
      } 
} 

一個JSON文件,我可以得到的對象,像這樣:

class SteveObject { 
    public int Steve; 
} 

var jsonSerializer = JsonSerializer.Create() 
var jsonFile = JObject.Parse(text); 
vat steveObject = jsonFile["Bob"].ToObject<SteveObject>(jsonSerializer) 

我該怎麼做同樣的事情YAMLDotNet或SharpYaml?即如果我有一個像

Bob: 
    Steve: 5 

YAML文件如何重建不同於SteveObject,而無需創建外部對象?

回答

0

好的,我寫了一些使用SharpYaml的代碼,它採用簡化的JPath查詢並返回請求的對象。

public static T ReadPath<T>(Serializer serializer, string yaml, string path) { 
     var eventReader = new EventReader(new Parser(new StringReader(yaml))); 

     var streamReader = new MemoryStream(Encoding.UTF8.GetBytes(path ?? "")); 
     if ((char)streamReader.ReadByte() != '$') 
      throw new Exception(); 

     if (streamReader.Position == streamReader.Length) 
      return serializer.Deserialize<T>(eventReader); 

     eventReader.Expect<StreamStart>(); 
     eventReader.Expect<DocumentStart>(); 

     while (streamReader.Position < streamReader.Length) { 
      if ((char)streamReader.ReadByte() != '.') 
       throw new Exception(); 

      eventReader.Expect<MappingStart>(); 

      var currentDepth = eventReader.CurrentDepth; 

      var nextKey = ReadPropertyName(streamReader); 
      if (string.IsNullOrEmpty(nextKey)) 
       throw new Exception(); 

      while (eventReader.Peek<Scalar>() == null || eventReader.Peek<Scalar>().Value != nextKey) { 
       eventReader.Skip(); 

       // We've left the current mapping without finding the key. 
       if (eventReader.CurrentDepth < currentDepth) 
        throw new Exception(); 
      } 

      eventReader.Expect<Scalar>(); 
     } 

     return serializer.Deserialize<T>(eventReader); 
    } 

    public static string ReadPropertyName(MemoryStream stream) { 
     var sb = new StringBuilder(); 

     while (stream.Position < stream.Length) { 
      var nextChar = (char) stream.ReadByte(); 
      if (nextChar == '.') { 
       stream.Position--; 
       return sb.ToString(); 
      } 

      sb.Append(nextChar); 
     } 

     return sb.ToString(); 
    } 

鑑於上述YAML以下工作:

var t = "Bob:\r\n Point: [1.0, 2.0, 3.0]\r\n Steve: 5\r\n"; 
var serializer = new Serializer(settings); 
var s = ReadPath<SteveObject>(serializer, t, "$.Bob"); // { "Steve": 5 } 
var s2 = ReadPath<int>(serializer, t, "$.Bob.Steve"); // 5 

當然希望有一個圖書館這一點,雖然。

相關問題