小编cry*_*eam的帖子

如何使用json.NET反序列化动态命名的根节点

这是json文件的一个示例:

{
   "John Smith": {
      "id": "72389",
      "email": "johnsmith@gmail.com",
      "books": [
         {
            "id": "0",
            "title": "The Hunger Games",
            "rating": "5"
         },
         {
            "id": "1",
            "title": "Harry Potter and the Order of the Phoenix",
            "rating": "3"
         },
      ],
      "magazines": [
         {
            "id": "2",
            "title": "National Geographic",
            "rating": "1"
         },
         {
            "id": "3",
            "title": "Wired",
            "rating": "4"
         }
      ],
   }
}
Run Code Online (Sandbox Code Playgroud)

请注意,根节点有一个动态名称(John Smith),我需要反序列化的每个json都有不同的名称.这个json结构需要按如下方式设置类:

public class RootObject
{
    public JohnSmith { get; set; }
}

public class JohnSmith //oops
{
    public string id …
Run Code Online (Sandbox Code Playgroud)

c# json.net deserialization

6
推荐指数
1
解决办法
4826
查看次数

如何检查T是否是泛型方法中的对象列表

我试图用Json.NET编写一个用于从json文件反序列化的通用方法
我希望能够支持反序列化包含对象和对象数组的文件.以下是我目前使用的两种通用方法的简化版本:

/// <summary>   Deserializes object or an array of objects from a list of files. </summary>
public static List<T> Deserialize<T>(List<string> filePathsList)
{
    var result = new List<T>();
    foreach (var file in filePathsList)
        // HOW DO I FIND OUT IF T IS A LIST HERE?
        // Resharper says: the given expression is never of the provided type
        if (typeof(T) is List<object>)
        {
            var deserialized = Deserialize<List<T>>(file);
            result.AddRange(deserialized);
        }
        // Resharper says: Suspicious type check: there is not type in the …
Run Code Online (Sandbox Code Playgroud)

.net c# generics

6
推荐指数
2
解决办法
4317
查看次数

标签 统计

c# ×2

.net ×1

deserialization ×1

generics ×1

json.net ×1