2015-12-02 417 views
1

我有一個json模式,我需要將它轉換爲C#對象或至少將其轉換爲json字符串。將Json Schema反序列化爲Json字符串或對象

有沒有辦法通過代碼或使用某種工具來做到這一點?

爲Json我目前使用Json.net

這是我的架構之一:

{ 
    "$schema": "http://json-schema.org/draft-04/schema#", 
    "title": "UserGroupWsDTO", 
    "type": "object", 
    "properties": 
    { 
    "members": 
    { 
     "type": "array", 
     "items": 
     { 
     "type": "object", 
     "properties": 
     { 
      "uid": 
      { 
      "type": "string" 
      } 
     } 
     } 
    }, 
    "uid": 
    { 
     "type": "string" 
    }, 
    "name": 
    { 
     "type": "string" 
    } 
    } 
} 

我需要這個創建反序列化對象的JSON

編輯 我的JSON模式的版本是4和JSON Schema來POCO沒有按」 t支持它

+0

轉到http://json2csharp.com/並粘貼你的json - 所有的類都將爲你創建。 – Ric

+1

可能重複[從JSON模式生成C#類](http://stackoverflow.com/questions/6358745/generate-c-sharp-classes-from-json-schema) – eoinmullan

+0

我不能使用json2csharp,因爲我有一個Json架構。 – frenk91

回答

0

如果你只是「瀏覽」key-values,那麼你不需要任何額外的庫...

只是做:

var obj = (JObject)JsonConvert.DeserializeObject(json); 

var dict = obj.First.First.Children().Cast<JProperty>() 
      .ToDictionary(p => p.Name, p =>p.Value); 

var dt = (string)dict["title"]; 

,但如果相反,你需要的字符串對象,然後定義一個類和反序列化串的那類......按照這個例子:

1定義類:

public class Uid 
{ 
    public string type { get; set; } 
} 

public class Properties2 
{ 
    public Uid uid { get; set; } 
} 

public class Items 
{ 
    public string type { get; set; } 
    public Properties2 properties { get; set; } 
} 

public class Members 
{ 
    public string type { get; set; } 
    public Items items { get; set; } 
} 

public class Uid2 
{ 
    public string type { get; set; } 
} 

public class Name 
{ 
    public string type { get; set; } 
} 

public class Properties 
{ 
    public Members members { get; set; } 
    public Uid2 uid { get; set; } 
    public Name name { get; set; } 
} 

public class RootObject 
{ 
    public string __invalid_name__$schema { get; set; } 
    public string title { get; set; } 
    public string type { get; set; } 
    public Properties properties { get; set; } 
} 

,這是實現:

string json = @"{...use your json string here }"; 

    RootObject root = JsonConvert.DeserializeObject<RootObject>(json); 

    Console.WriteLine(root.title); 
    // UserGroupWsDTO 
+0

我需要一個反序列化JSON的對象 – frenk91

+0

我的問題是如何獲得一個JSON,因爲否則爲了創建我需要的「Account」對象閱讀Json模式 – frenk91

+0

@ frenk91,新的更改,所以請再次看看更新的答案。 –

相關問題