2016-10-13 46 views
1

我有麻煩反序列化json我有一個@符號在許多屬性名稱的開頭。這是很多json,所以我不知道是否從json中刪除所有@是安全的,或者如果我將失去與屬性相關的值中的一些有價值的信息。例如,我嘗試使用[JsonProperty("@fontName")],但沒有奏效(C#對象沒有采用我在JSON中看到的值;而是使用null代替)。如何將json反序列化爲屬性名稱開頭具有「@」的C#對象?

internal static RootObject MyMethod(string json) 
{ 
    var rootObject = JsonConvert.DeserializeObject<RootObject>(json); 
    return rootObject; 
} 

這是我處理的JSON的一個片段:

{ 
    "document": { 
    "page": [ 
     { 
     "@index": "0", 
     "row": [ 
      { 
      "column": [ 
       { 
       "text": "" 
       }, 
       { 
       "text": { 
        "@fontName": "Times New Roman", 
        "@fontSize": "8.0", 
        "@x": "133", 
        "@y": "14", 
        "@width": "71", 
        "@height": "8", 
        "#text": "FINAL STATEMENT" 
       } 
... 

這裏是什麼,我想反序列化到一個例子:

public class Column 
{ 
    [JsonProperty("@fontName")] 
    public string fontName { get; set; } 
    public object text { get; set; } 
} 

public class Row 
{ 
    public List<Column> column { get; set; } 
    public string text { get; set; } 
} 

public class Page 
{ 
    public string index { get; set; } 
    public List<Row> row { get; set; } 
    public string text { get; set; } 
} 

public class Document 
{ 
    public List<Page> page { get; set; } 
} 

public class RootObject 
{ 
    public Document document { get; set; } 
} 
+0

我的回答對你有幫助嗎? – mybirthname

+0

_that不工作是什麼意思?究竟發生了什麼?同樣,在下面的答案中,@mybirthname暗示,你需要想出一種方法來讓'Text'保存一個複雜類型或一個字符串。 –

+0

@mybirthname,我會在今晚或明天嘗試一下,並會讓你知道。這與我上面嘗試的方法類似,但這並不奏效,但我會嘗試查看是否錯過了某些內容。 @AndrewWhitaker,它不起作用意味着當我得到C#對象時,我預期在該屬性中保留的信息是'null'。反序列化(作爲黑盒子)並沒有奏效,因爲我的輸入沒有產生預期的輸出。 –

回答

0

從我所看到的你錯過了你的Page對象的屬性index屬性。

這樣寫[JsonProperty(PropertyName ="@index")]最好理解。我們也看不到fontName,fontSize,x,y等的定義,單獨Text類。出於某種原因,你把它當作對象來寫。

public class Text 
{ 
    [JsonProperty(PropertyName ="@fontName")] 
    public string FontName {get; set;} 

    [JsonProperty(PropertyName ="@fontSize")] 
    public string FontSize {get; set;} 

    [JsonProperty(PropertyName ="#text")] 
    public string TextResult{get; set;} 

    //other objects 
} 

public class Column 
{ 
    public List<Text> text { get; set; } 
} 
+0

這種方法很有意義。我會盡快再試一次。只是想提一下,這正是我已經用'fontName'屬性嘗試過的東西。我沒有把'JsonProperty'裝飾器/屬性放在其他屬性上的原因是純粹的懶惰。直到我向自己證明那是我需要做的事情之前,我不想把這些全部放在一起。由於它不適用於'fontName',我認爲它不適用於其餘的。 –

相關問題