如何从json创建一个c#对象

时间:2013-08-29 15:01:05

标签: c# .net 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
}

json-object必须如何反序列化?

或者是否有另一种获取属性值的方法?

4 个答案:

答案 0 :(得分:7)

使用JSON.NET库非常简单:

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

然后:

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

在这个例子中,我使用Dictionary<string, Data>对象来建模2个复合键(foo.hugo.infofoo.Fritz.Task),因为它们包含不能在.NET成员中使用的名称。 / p>

答案 1 :(得分:5)

如果您使用的是VS2012或更高版本,则可以执行以下操作:

Edit > Paste Special > Paste JSON As Classes

以您的示例为例,结果如下:

public class Rootobject
{
    public Data data { get; set; }
    public bool success { get; set; }
}

public class Data
{
    public FooHugoInfo foohugoinfo { get; set; }
    public FooFritzTask fooFritzTask { get; set; }
}

public class FooHugoInfo
{
    public string path { get; set; }
    public int minVersion { get; set; }
    public int maxVersion { get; set; }
}

public class FooFritzTask
{
    public string path { get; set; }
    public int minVersion { get; set; }
    public int maxVersion { get; set; }
}

答案 2 :(得分:1)

查看此网站:http://json2csharp.com/

粘贴在json字符串中,它将为您生成类。我通常使用JSON.NET来反序列化根对象的实例。

答案 3 :(得分:1)

您可以使用DataContractJsonSerializer

    [DataContract]
    public class DetailedData
    {
        [DataMember(Name="path")]
        public string Path { get; set; }
        [DataMember(Name = "minVersion")]
        public int MinVersion { get; set; }
        [DataMember(Name = "maxVersion")]
        public int MaxVersion { get; set; }
    }

    [DataContract]
    public class Data
    {
        [DataMember(Name = "foo.hugo.info")]
        public DetailedData Info { get; set; }
        [DataMember(Name = "foo.Fritz.Task")]
        public DetailedData Task { get; set; }
    }

    [DataContract]
    public class RootObject
    {
        [DataMember(Name = "data")]
        public Data Data { get; set; }
        [DataMember(Name = "success")]
        public bool Success { get; set; }
    }

    static void Main(string[] args)
    {
        string json = "...";
        DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(RootObject));

        RootObject obj = (RootObject)js.ReadObject(new MemoryStream(Encoding.Unicode.GetBytes(json)));
        Console.WriteLine(obj.Data.Task.MaxVersion); 
    }

修改:InfoTask

的同一课程