将Json代码转换为C#(数字作为键)

时间:2013-04-17 12:32:48

标签: c# json windows-phone-8 entity

我从Windows Phone 8中的Web服务获取了一些json代码。由于站点json2csharp(http://json2csharp.com/),我生成了我的实体类。但是有一个Web服务有奇怪的json代码,就像这样。编号为键(0,1,2):

{
  "service": "MainMapService",
  "func": "getPlacesByAxes",
  "result": {
    "0": {
      "id": "13478",
      "date": "0",
      "id_cat": "1",
      "id_cat_sub": "0",
      "id_user": "0",
     },
    "2": {
      "id": "23272",
      "date": "0",
      "id_cat": "1",
      "id_cat_sub": "0",
      "id_user": "667"
    },
    "1": {
      "id": "21473",
      "date": "0",
      "id_cat": "1",
      "id_cat_sub": "0",
      "id_user": "0"
     }
   },
  "args": [
    "1",
    "50.8",
    "4.5",
    "1"
  ]
}

json2csharp生成这样的类......每个类都有一个数字:

public class __invalid_type__0
{
    public string id { get; set; }
    public string date { get; set; }
    public string id_cat { get; set; }
    public string id_cat_sub { get; set; }
    public string id_user { get; set; }
}

public class __invalid_type__2
{
    public string id { get; set; }
    public string date { get; set; }
    public string id_cat { get; set; }
    public string id_cat_sub { get; set; }
    public string id_user { get; set; }
}

public class __invalid_type__1
{
    public string id { get; set; }
    public string date { get; set; }
    public string id_cat { get; set; }
    public string id_cat_sub { get; set; }
    public string id_user { get; set; }
}

public class Result
{
    public __invalid_type__0 __invalid_name__0 { get; set; }
    public __invalid_type__2 __invalid_name__2 { get; set; }
    public __invalid_type__1 __invalid_name__1 { get; set; }
}

public class RootObject
{
    public string service { get; set; }
    public string func { get; set; }
    public Result result { get; set; }
    public List<string> args { get; set; }
}

因此,问题来自编号键,可能有几个数字。你知道我怎么解决这个问题?我不能改变Json代码...

提前谢谢

1 个答案:

答案 0 :(得分:1)

这远非优雅,但试一试。

那么,我的想法是什么:

我创建了两个类

RootObject帮助

public class YourJsonClass
{
  public string service { get; set; }
  public string func { get; set; }
  public dynamic result { get; set; }
  public string[] args { get; set; }
}

result帮助

public class Item
        {
            public string id { get; set; }
            public string date { get; set; }
            public string id_cat { get; set; }
            public string id_cat_sub { get; set; }
            public string id_user { get; set; }
        }

我正在使用newtonsoft json

 var m_res = JsonConvert.DeserializeObject<YourJsonClass>(YourJsonResponce);        
            foreach (dynamic numb in m_res.result)
            {

                string m_name = numb.Name; // it will be "1", "0" or whatever
                string h = numb.Value.ToString();
                var m_value = JsonConvert.DeserializeObject<Item>(h);

            }

......确实有更好的方法,但我希望这会有所帮助(: