Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an c# object from json

Tags:

json

c#

.net

I get the following response from a webservice:

{
  "data":{
    "foo.hugo.info": {
      "path": "logon.cgi",
      "minVersion": 1,
      "maxVersion": 2
    },
    "foo.Fritz.Task": {
      "path": "Fritz/process.cgi",
      "minVersion": 1,
      "maxVersion": 1
    }
  },
  "success": true
}

How must the json-object look like to deserialize this?

Or is there another way to get the values of the properties?

like image 304
GreenEyedAndy Avatar asked Aug 29 '13 15:08

GreenEyedAndy


1 Answers

With the JSON.NET library it's pretty trivial:

public class Root
{
    public Dictionary<string, Data> Data { get; set; }
    public bool Success { get; set; }
}

public class Data
{
    public string Path { get; set; }
    public int MinVersion { get; set; }
    public int MaxVersion { get; set; }
}

and then:

string json = 
@"{
  ""data"":{
    ""foo.hugo.info"": {
      ""path"": ""logon.cgi"",
      ""minVersion"": 1,
      ""maxVersion"": 2
    },
    ""foo.Fritz.Task"": {
      ""path"": ""Fritz/process.cgi"",
      ""minVersion"": 1,
      ""maxVersion"": 1
    }
  },
  ""success"": true
}";
Root root = JsonConvert.DeserializeObject<Root>(json);

In this example I have used a Dictionary<string, Data> object to model the 2 complex keys (foo.hugo.info and foo.Fritz.Task) because they contain names that cannot be used in a .NET member.

like image 113
Darin Dimitrov Avatar answered Sep 27 '22 21:09

Darin Dimitrov