0

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"
      }
    ]
  }
}
5
  • the C# property would look like this and it does not work Commented Mar 19, 2014 at 13:04
  • public List<Testnetwork> 10.0.0.1/24 { get; set; } Commented Mar 19, 2014 at 13:05
  • @Jebanisa..I guess you need to create a class for Ip Address with all the three fields? Commented Mar 19, 2014 at 13:05
  • Shouldn't addresses be an array? Are you sure that always only 1 ip address range is coming in your json? Commented Mar 19, 2014 at 13:18
  • The problem is that when I Deserialize the json it tries to map the "10.0.0.1/24" to a list in my c# class but because the json name is "10.0.0.1/24" it does not map it correctly Commented Mar 19, 2014 at 13:28

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. Excellent answer and it works in my environment. If I could kiss you, I would! <3
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.