簡體   English   中英

JSON屬性無法在C#類中映射

[英]JSON property can't map in C# class

我有這個無法更改的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"
      }
    ]
  }
}

由於對象包含無法在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;
    }
}

這是使用System.Web.Script.Serialization命名空間中的JavaScriptSeralizer完成的,但類似的方法可以通過Netonsoft Json庫或其他正在使用的庫來完成。

關鍵是要確保將屬性映射到json屬性作為對象的sting鍵或通過序列化屬性。

您將不得不使用像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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM