简体   繁体   中英

JSON property can't map in C# class

I have this JSON code which can't be changed. I want to make a C# class out of it but the problem I'm having is that the 10.0.0.1/24 can't be made into a C# class property and the 10.0.0.1/24 could be any ip address range.

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

As the object contains properties that cannot be legally named in C# you need to either wrap them as string indexes or use an attribute the specify the property name.

Firstly, you need to declare the objects to use

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

I have opted to use a Dictionary<string, List<Bar>> combination for the list of addresses. The key will be 10.0.0.1/24 in your example. The property OST-EXT-IPS:type cannot be legally translated, so this uses the attribute option.

The class can then be deseralised as

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

This has been done using the JavaScriptSeralizer in the System.Web.Script.Serialization namespace, but a similar approach can be done via Netonsoft Json library or other libraries in use.

The key is to ensure that properties are mapped to a json attribute as either sting key of an object or via a serialisation attribute.

You will have to use a serialization framework like NewtonSoft JSON . This framework is used by default in some Microsoft projects like WebAPI or SignalR, so it is not strange.

You can install it with NuGet: http://www.nuget.org/packages/Newtonsoft.Json

With this framework, you can use LINQ to JSON to deserialize the object yourself in your own way: 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM