如何将json反序列化为具有" @"的C#对象?在属性名称的开头?

时间:2016-10-13 01:49:05

标签: c# json.net deserialization

我无法反序列化json我在很多属性名称的开头有一个@符号。这是很多json所以我不知道从json中删除所有@是否安全,或者我是否会丢失与属性相关的值中的一些有价值的信息。

我尝试使用[JsonProperty("@fontName")],但是没有用(C#对象没有采用我在JSON中看到的值;而是null而是)。< / p>

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; }
}

1 个答案:

答案 0 :(得分:0)

据我所知,您错过了index对象的某个属性Page属性。

以这种方式书写[JsonProperty(PropertyName ="@index")]最好理解。另外,我们在单独的fontName类中没有看到fontSizexyText等的定义。出于某种原因,你把它写成了对象。

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; }
}