JSON属性无法在C#类中映射

时间:2014-03-19 13:00:04

标签: c# json

我有这个JSON代码无法更改。我想从中创建一个C#类,但我遇到的问题是10.0.0.1/24不能被制作成C#类属性而且 10.0.0.1/24可以是任何IP地址范围。

{
  "addresses": {
    "10.0.0.1/24": [
      {
        "version": 4,
        "addr": "10.0.0.36",
        "OS-EXT-IPS:type": "fixed"
      }
    ]
  }
}

2 个答案:

答案 0 :(得分:2)

由于对象包含无法在C#中合法命名的属性,您需要将它们包装为字符串索引或使用属性指定属性名称。

首先,您需要声明要使用的对象

public class Foo
{
    public Dictionary<string, List<Bar>> addresses { get; set; }
}

public class Bar
{
    public int version { get; set; }
    public string addr { get; set; }

    [DataMember(Name = "OS-EXT-IPS:type")]
    public string OstType { get; set; }
}

我选择使用Dictionary<string, List<Bar>>组合作为地址列表。您的示例中的密钥为10.0.0.1/24。属性OST-EXT-IPS:type无法合法翻译,因此使用属性选项。

然后可以将该类解除为

public static string JsonExtract()
{
    Foo obj = new Foo();
    obj.addresses = new Dictionary<string, List<Bar>>() { { "10.0.0.1/24", new List<Bar>() { new Bar() { version = 4, addr = "10.0.0.36", OstType = "fixed" } } }};

    JavaScriptSerializer js = new JavaScriptSerializer();
    string s = js.Serialize(obj);

    return s;
}

public static Foo JsonParse()
{
    string file = @"json.txt"; // source
    using (StreamReader rdr = new StreamReader(file))
    {
        string json = rdr.ReadToEnd();
        JavaScriptSerializer js = new JavaScriptSerializer();
        Foo obj = js.Deserialize<Foo>(json);

        return obj;
    }
}

这是使用JavaScriptSeralizer命名空间中的System.Web.Script.Serialization完成的,但类似的方法可以通过Netonsoft Json库或其他正在使用的库来完成。

关键是要确保属性作为对象的sting键或通过序列化属性映射到json属性。

答案 1 :(得分:0)

您必须使用像NewtonSoft JSON这样的序列化框架。默认情况下,此框架在某些Microsoft项目(如WebAPI或SignalR)中使用,因此并不奇怪。

您可以使用NuGet安装它:http://www.nuget.org/packages/Newtonsoft.Json

使用此框架,您可以使用LINQ to JSON以您自己的方式自行反序列化对象:http://james.newtonking.com/json/help/index.html?topic=html/QueryingLINQtoJSON.htm

 string json = @"{
  'channel': {
    'title': 'James Newton-King',
    'link': 'http://james.newtonking.com',
    'description': 'James Newton-King\'s blog.',
    'item': [
      {
        'title': 'Json.NET 1.3 + New license + Now on CodePlex',
        'description': 'Annoucing the release of Json.NET 1.3, the MIT license and the source on CodePlex',
        'link': 'http://james.newtonking.com/projects/json-net.aspx',
        'category': [
          'Json.NET',
          'CodePlex'
        ]
      },
      {
        'title': 'LINQ to JSON beta',
        'description': 'Annoucing LINQ to JSON',
        'link': 'http://james.newtonking.com/projects/json-net.aspx',
        'category': [
          'Json.NET',
          'LINQ'
        ]
      }
    ]
  }
}";

JObject rss = JObject.Parse(json);

var postTitles =
    from p in rss["channel"]["item"]
    select (string)p["title"];

foreach (var item in postTitles)
{
    Console.WriteLine(item);
}
//LINQ to JSON beta
//Json.NET 1.3 + New license + Now on CodePlex

var categories =
    from c in rss["channel"]["item"].Children()["category"].Values<string>()
    group c by c
    into g
    orderby g.Count() descending
    select new { Category = g.Key, Count = g.Count() };

foreach (var c in categories)
{
    Console.WriteLine(c.Category + " - Count: " + c.Count);
}
//Json.NET - Count: 2