JSON Newtonsoft C#序列化/反序列化对象列表的良好实践 [英] JSON Newtonsoft C# Good Practice for Serialize/ Deserialize Lists of Objects

查看:82
本文介绍了JSON Newtonsoft C#序列化/反序列化对象列表的良好实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在这里阅读了有关此问题的其他帖子

I've readed others posts here about this question

使用Json.NET对对象列表进行序列化

将列表序列化为JSON

在使用json.net进行序列化期间合并两个对象吗?

所有都很有用.当然,我可以在一个json两个列表中进行序列化,但无法对其进行反序列化.

All very useful. Certain, I can serialize in one json two lists, but I cant deserialize it.

我正在使用Json Newtonsoft,C#,MVC5,框架4.5.这是场景:

I´m working with Json Newtonsoft, C#, MVC5, framework 4.5. This is the scenario:

C#代码

public class User
{
    public int id { get; set; }
    public string name { get; set; }
}

public class Request
{
    public int id { get; set; }
    public int idUSer{ get; set; } 
}

List<User> UserList = new List<User>();          
List<Request> RequestList = new List<Request>();
string json=  JsonConvert.SerializeObject(new { UserList, RequestList });

JSON结果

{
"UserList":[
  {
     "id":1,
     "name":"User 1"
  },
  {
     "id":2,
     "name":"User 2"
  },
  {
     "id":3,
     "name":"User 3"
  }
 ],
"RequestList":[
  {
     "id":1,
     "idUSer":1
  },
  {
     "id":2,
     "idUSer":1
  },
  {
     "id":3,
     "idUSer":1
  },
  {
     "id":4,
     "idUSer":2
  }
  ]
  }

C#反序列化

我不知道如何配置Json.Deserialize<?,Settings>(json)表示要反序列化哪些类型的对象.

I dont Know how configure the settings of Json.Deserialize< ?, Settings>(json) for indicate what types of objects are being deserialized.

方法的改变

因此,为了改变方法,我创建了一个新的"Cover"类,以便将列表放在一起并序列化一个对象

So that, change of approach, I've created a new class "Cover" in order to put the lists together and serialize one object

 public class Cover
 {
    private List<User> user = new List<User>();
    private List<Request> request = new List<Request>();

    public List<User> User 
    { 
        get { return user;}
        set { User = value;}        
    }      

    public List<Request> Request
    {
        get {return request;}
        set {Request = value;}
    }
  }

SERIALIZE

string json = JsonConvert.SerializeObject(cover);

JSON JSON结果是相同的.

JSON The json result is the same.

反序列化

 Cover  result = JsonConvert.DeserializeObject<Cover>(json, new 
 JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto });

一切正常.我的情况已经解决,但是我对概念有疑问,在我看来尚不清楚:

It's work fine. My situation is resolved but I have doubts about concepts, in my mind something is not clear:

我的问题是:

第一个方法:

您认为有一种方法可以用不同的对象列表反序列化json吗?这不是一个好习惯吗?

Do you think that there is a way to deserialize a json with different lists of objects? Is not a good practice?

第二种方式:为什么json在第一种情况下是相等的?

Second aproach: Why jsons are equals for first situation?

推荐答案

在JSON.NET中,您需要提供要反序列化的类型,方法是将其名称作为类型参数提供给 DeserializeObject .但是,在这一行:

In JSON.NET you need to specify the type you're about to deserialize, by supplying its name as a type argument to DeserializeObject. However, in this line:

string json=  JsonConvert.SerializeObject(new { UserList, RequestList });

您创建匿名对象,然后对其进行序列化- new {UserList,RequestList} .因此有一个陷阱-您不能使用匿名类型作为类型参数.为了处理这种情况,JSON.NET提供了 DeserializeAnonymousType<> .它不需要您提供type参数.实际上,您将无法反序列化匿名类型.相反,它是根据传递给方法的第二个参数的类型推断出来的.因此,您只需创建一个没有数据的虚拟匿名对象,然后将其传递给此方法即可.

you create anonymous object and then serialize it - new { UserList, RequestList }. So there is the catch - you cannot use anonymous type as type arguments. To handle such situations, JSON.NET provides DeserializeAnonymousType<>. It doesn't require you to supply the type argument; actually you can't as you going to deserialize anonymous type. Instead it is inferred from the type of the second argument, passed to the method. So you just create a dummy, anonymous object, without data and pass it to this method.

// jsonData contains previously serialized List<User> and List<Request>
void DeserializeUserAndRequest(string jsonData) 
{
    var deserializedLists = new { 
        UserList = new List<User>(), 
        RequestList = new List<Request>() 
    };
    deserializedLists = JsonConvert.DeserializeAnonymousType(jsonData, deserializedLists);

    // Do your stuff here by accessing 
    //  deserializedLists.UserList and deserializedLists.RequestLists
}

当然,这一切都很好,但是这种方法表明您已经知道序列化数据的结构.如果此结构与您通过匿名类型初始化的结构不匹配,则在 DeserializeAnonymousType 方法之后您将一无所获.这不仅对匿名类型的属性类型有效,对名称也有效.

Of course this all works fine, but this approach suggests that you already know the structure of the serialized data. If this structure doesn't match the structure of the initialized by you anonymous type you'll get nothing after the DeserializeAnonymousType method. And this is valid not just for the type of the properties of the anonymous type, but for their names too.

这篇关于JSON Newtonsoft C#序列化/反序列化对象列表的良好实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆