我应该如何创建我的json类来用c#解析它?

时间:2014-01-02 22:00:19

标签: c# json json.net

我已经使用了几个json到C#转换器来生成类,所以我可以用

反序列化它
var foo = JsonConvert.DeserializeObject<someGeneratedType>(jsonString);

但是我似乎无法填充结果。 query-continue 对象应具有 usercontribs ,其 ucstart 具有值。

然后我应该得到一个查询对象,该对象有3个 usercontribs 。如果有人可以帮我解决这个问题,我会非常感激。

{
  "query-continue": {
    "usercontribs": {
      "ucstart": "2013-07-18T02:24:25Z"
    }
  },
  "query": {
    "usercontribs": [
      {
        "userid": "666777",
        "user": "UserYahoo",
        "pageid": 22255,
        "revid": 555566666,
        "parentid": 555577777,
        "ns": 0,
        "title": "Title A",
        "timestamp": "2013-07-16T01:13:32Z",
        "comment": "/* Comment A */",
        "size": 62789
      },
      {
        "userid": "666777",
        "user": "UserYahoo",
        "pageid": 22255,
        "revid": 564444444,
        "parentid": 555566666,
        "ns": 0,
        "title": "Title A",
        "timestamp": "2013-07-16T01:28:50Z",
        "comment": "/* Comment B */",
        "size": 62794
      },
      {
        "userid": "666777",
        "user": "UserYahoo",
        "pageid": 11777,
        "revid": 564333333,
        "parentid": 444499999,
        "ns": 0,
        "title": "Title B",
        "timestamp": "2013-07-17T03:28:50Z",
        "comment": "/* Comment C */",
        "size": 10865
      }
    ]
  }
}

1 个答案:

答案 0 :(得分:1)

根元素“query-continue”不响应C#中的命名规则属性。大多数反序列化sdk使用反射,在这种情况下是不可能的。 我在“query-continue”属性上没有破折号测试了你的样本,它运行正常。

public class Usercontribs
    {
        public string ucstart { get; set; }
    }

    public class Querycontinue
    {
        public Usercontribs usercontribs { get; set; }
    }

    public class Usercontrib
    {
        public string userid { get; set; }
        public string user { get; set; }
        public int pageid { get; set; }
        public int revid { get; set; }
        public int parentid { get; set; }
        public int ns { get; set; }
        public string title { get; set; }
        public string timestamp { get; set; }
        public string comment { get; set; }
        public int size { get; set; }
    }

    public class Query
    {
        public List<Usercontrib> usercontribs { get; set; }
    }

    public class RootObject
    {
        public Querycontinue querycontinue { get; set; }
        public Query query { get; set; }
    }

我测试一下:

Stream fs = File.OpenRead(@"C:\Users\Dell\Downloads\sample.txt");

DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(RootObject));
RootObject v_response = (RootObject)jsonSerializer.ReadObject(fs);