如何在 C# .NET 中反序列化复杂的 JSON 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16339167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:48:19  来源:igfitidea点击:

How do I deserialize a complex JSON object in C# .NET?

c#.netjsondeserialization

提问by Assaf Zigdon

I have a JSON string and I need some help to deserialize it.

我有一个 JSON 字符串,我需要一些帮助来反序列化它。

Nothing worked for me... This is the JSON:

没有什么对我有用......这是JSON:

{
    "response": [{
        "loopa": "81ED1A646S894309CA1746FD6B57E5BB46EC18D1FAff",
        "drupa": "D4492C3CCE7D6F839B2BASD2F08577F89A27B4ff",
        "images": [{
                "report": {
                    "nemo": "unknown"
                },
                "status": "rock",
                "id": "7e6ffe36e-8789e-4c235-87044-56378f08m30df",
                "market": 1
            },
            {
                "report": {
                    "nemo": "unknown"
                },
                "status": "rock",
                "id": "e50e99df3-59563-45673-afj79e-e3f47504sb55e2",
                "market": 1
            }
        ]
    }]
}

I have an example of the classes, but I don't have to use those classes. I don't mind using some other classes.

我有一个类的示例,但我不必使用这些类。我不介意使用其他一些类。

These are the classes:

这些是类:

public class Report
{
    public string nemo { get; set; }
}

public class Image
{
    public Report report { get; set; }
    public string status { get; set; }
    public string id { get; set; }
    public int market { get; set; }
}

public class Response
{
    public string loopa { get; set; }
    public string drupa{ get; set; }
    public Image[] images { get; set; }
}

public class RootObject
{
    public Response[] response { get; set; }
}

I want to mention that I have Newtonsoft.Json already, so I can use some functions from there.

我想提一下,我已经有了 Newtonsoft.Json,所以我可以使用那里的一些功能。

How can I do this?

我怎样才能做到这一点?

采纳答案by Javal Patel

I am using like this in my code and it's working fine

我在我的代码中使用这样的,它工作正常

below is a piece of code which you need to write

下面是一段你需要编写的代码

using System.Web.Script.Serialization;

JavaScriptSerializer oJS = new JavaScriptSerializer();
RootObject oRootObject = new RootObject();
oRootObject = oJS.Deserialize<RootObject>(Your JSon String);

回答by stevepkr84

Should just be this:

应该只是这样:

var jobject = JsonConvert.DeserializeObject<RootObject>(jsonstring);

You can paste the json string to here: http://json2csharp.com/to check your classes are correct.

您可以将 json 字符串粘贴到此处:http: //json2csharp.com/以检查您的类是否正确。

回答by filipko

If you use C# 2010 or newer, you can use dynamic type:

如果您使用 C# 2010 或更新版本,则可以使用动态类型

dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonstring);

Then you can access attributes and arrays in dynamic object using dot notation:

然后您可以使用点表示法访问动态对象中的属性和数组:

string nemo = json.response[0].images[0].report.nemo;

回答by Uzzy

I am using following:

我正在使用以下内容:

    using System.Web.Script.Serialization;       

    ...

    public static T ParseResponse<T>(string data)
    {
        return new JavaScriptSerializer().Deserialize<T>(data);
    }

回答by Ozesh

I had a scenario, and this one helped me

我有一个场景,这个场景帮助了我

JObjectobjParserd = JObject.Parse(jsonString);

JObjectobjParserd = JObject.Parse(jsonString);

JObjectarrayObject1 = (JObject)objParserd["d"];

JObjectarrayObject1 = ( JObject)objParserd["d"];

DmyOutput= JsonConvert.DeserializeObject<D>(arrayObject1.ToString());

DmyOutput= JsonConvert.DeserializeObject <D>(arrayObject1.ToString());

回答by Tejas Jain

First install newtonsoft.jsonpackage to Visual Studiousing NuGet Package Managerthen add the following code:

首先安装newtonsoft.jsonVisual Studio使用的包,NuGet Package Manager然后添加以下代码:

ClassName ObjectName = JsonConvert.DeserializeObject < ClassName > (jsonObject);

回答by Veera Induvasi

shareInfo is Class:

shareInfo 是类:

public class ShareInfo
        {
            [JsonIgnore]
            public readonly DateTime Timestamp = DateTime.Now;
            [JsonProperty("sharename")]
            public string ShareName = null;
            [JsonProperty("readystate")]
            public string ReadyState = null;
            [JsonProperty("created")]
            [JsonConverter(typeof(Newtonsoft.Json.Converters.UnixDateTimeConverter))]
            public DateTime? CreatedUtc = null;
            [JsonProperty("title")]
            public string Title = null;
            [JsonProperty("getturl")]
            public string GettUrl = null;
            [JsonProperty("userid")]
            public string UserId = null;
            [JsonProperty("fullname")]
            public string Fullname = null;
            [JsonProperty("files")]
            public GettFile.FileInfo[] Files = new GettFile.FileInfo[0];
        }

// POST request.
            var gett = new WebClient { Encoding = Encoding.UTF8 };
            gett.Headers.Add("Content-Type", "application/json");
            byte[] request = Encoding.UTF8.GetBytes(jsonArgument.ToString());
            byte[] response = gett.UploadData(baseUri.Uri, request);

            // Response.
            var shareInfo = JsonConvert.DeserializeObject<ShareInfo>(Encoding.UTF8.GetString(response));

回答by Veera Induvasi

 public static void Main(string[] args)
{
    string json = @" {
    ""children"": [
            {
        ""url"": ""foo.pdf"", 
                ""expanded"": false, 
                ""label"": ""E14288-Passive-40085-2014_09_26.pdf"", 
                ""last_modified"": ""2014-09-28T11:19:49.000Z"", 
                ""type"": 1, 
                ""size"": 60929
            }
        ]
     }";




    var result = JsonConvert.DeserializeObject<ChildrenRootObject>(json);
    DataTable tbl = DataTableFromObject(result.children);
}

public static DataTable DataTableFromObject<T>(IList<T> list)
{
    DataTable tbl = new DataTable();
    tbl.TableName = typeof(T).Name;

    var propertyInfos = typeof(T).GetProperties();
    List<string> columnNames = new List<string>();

    foreach (PropertyInfo propertyInfo in propertyInfos)
    {
        tbl.Columns.Add(propertyInfo.Name, propertyInfo.PropertyType);
        columnNames.Add(propertyInfo.Name);
    }

    foreach(var item in list)
    {
        DataRow row = tbl.NewRow();
        foreach (var name in columnNames)
        {
            row[name] = item.GetType().GetProperty(name).GetValue(item, null);
        }

        tbl.Rows.Add(row);
    }

    return tbl;
}

public class Child
{
    public string url { get; set; }
    public bool expanded { get; set; }
    public string label { get; set; }
    public DateTime last_modified { get; set; }
    public int type { get; set; }
    public int size { get; set; }
}

public class ChildrenRootObject
{
    public List<Child> children { get; set; }
}

回答by everydayXpert

I solved this problem to add a public setter for all properties, which should be deserialized.

我解决了这个问题,为所有应该反序列化的属性添加了一个公共设置器。

回答by Mahdi ghafoorian

You can solve your problem like below bunch of codes

你可以像下面的一堆代码一样解决你的问题

public class Response
{
    public string loopa { get; set; }
    public string drupa{ get; set; }
    public Image[] images { get; set; }
}

public class RootObject<T>
    {
        public List<T> response{ get; set; }

    }

var des = (RootObject<Response>)Newtonsoft.Json.JsonConvert.DeserializeObject(Your JSon String, typeof(RootObject<Response>));