简体   繁体   English

是否可以反序列化为属性而不是对象

[英]Is it possible to deserialize into property rather than an object

Appologies if its already been asked, I could not find anything helpful to my situation. 如果已经提出了要求,我找不到任何对我的情况有用的东西。

I need to deserialize a JSON in a property of my object instead of a whole object. 我需要在我的对象的属性而非整个对象的属性中反序列化JSON。 The reason I am trying to do it, is that is simply generics. 我尝试这样做的原因是,这只是泛型。

I have the following situation 我有以下情况

For instance I have 例如我有

Class User 
{
   int UserId {get;set;}
   string Name {get;set;
}

Class Wanted : CustomClass
{
   User[] Users {get;set;}

   public override void Map(){ } 
   public override void Scan(){ }
}

My Json is: 我的杰森是:

[
  {
    "userId": 1,
    "name": "Josh"
  },
  {
    "userId": 5,
    "name" : "Martin"
  }
]

Is it possible to deserialize(+ generics) my JSON directly into my Wanted class instead of serializing into A and then assign it into Wanted ? 是否可以将我的JSON直接反序列化(+泛型)到我的Wanted类中,而不是序列化为A然后再将其分配给Wanted中?

The goal is after the serialization I will have object with type Wanted and an array with 2 users in it. 目标是在序列化之后,我将拥有类型为Wanted的对象和其中包含2个用户的数组。

Since the JSON does not match the class you want to deserialize into, and you cannot change the JSON, you will need to use a custom JsonConverter to bridge the gap. 由于JSON与您要反序列化的类不匹配,并且您无法更改JSON,因此需要使用自定义JsonConverter来弥合差距。

To make it work you'll need to introduce an interface IHasUsers which your Wanted class (or its base class) will need to implement: 为了使其正常工作,您需要引入一个IHasUsers接口,您的Wanted类(或其基类)将需要实现:

interface IHasUsers
{
    User[] Users { get; set; }
}

class Wanted : CustomClass, IHasUsers
{
    public User[] Users { get; set; }
    ...
}

Then you can make a generic converter which will instantiate the Wanted class (or any other class which implements IHasUsers ) and populate the Users property: 然后,您可以创建一个通用转换器,该转换器将实例化Wanted类(或实现IHasUsers任何其他类)并填充Users属性:

class UserListConverter<T> : JsonConverter where T: IHasUsers, new()
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(IHasUsers).IsAssignableFrom(objectType);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JArray array = JArray.Load(reader);
        T obj = new T() { Users = array.ToObject<User[]>() };
        return obj;
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Then you can deserialize your JSON like this: 然后,您可以像这样反序列化JSON:

Wanted wanted = JsonConvert.DeserializeObject<Wanted>(json, new UserListConverter<Wanted>());

Here is a demo: https://dotnetfiddle.net/KL6Ok6 这是一个演示: https : //dotnetfiddle.net/KL6Ok6

Hope this is what you were looking for. 希望这就是您想要的。

Since Wanted is "your desired class", there needs to be an instance of Wanted created somewhere. 由于Wanted是“您所需的类”,因此需要在某个地方创建一个Wanted实例。 You might just as well create it yourself rather than having a derserializer do it for you. 您也可以自己创建它,而不是使用解串器为您完成。 Once you have done this you can simply set the Users property to the deserialized data: 完成此操作后,您可以简单地将Users属性设置为反序列化数据:

var wanted = new Wanted() { Users = JsonConvert.DeSerialize<User[]>(myString) };

You don't deserialize some data "into a property" without deserializing it to some object of some type first. 您无需先将某些数据反序列化为“属性”,而无需将其反序列化为某种类型的对象。 Once you have done this you can then set the property to the object that contains the deserialized data. 完成此操作后,您可以将属性设置为包含反序列化数据的对象。

There is nothing generic about Wanted here though and the deserializer cannot be supposed to figure out that it should create a Wanted or any other type unless you specify the type to derserialize the data to somewhere. 但是,这里并没有通用的Wanted犯,并且除非您指定将数据反序列化到某个地方的类型,否则反序列化器不能假定它应该创建Wanted犯或任何其他类型。

And there is no point of deserializing the data to a type defined at compile time if you don't know that the data matches this type. 如果您不知道数据与该类型匹配,则没有必要将数据反序列化为在编译时定义的类型。 Then you might as well create an anonymous object or a dictionary of key/value pairs. 然后,您还可以创建一个匿名对象或键/值对的字典。

You can use Newtonsoft.json . 您可以使用Newtonsoft.json。 Try below 试试下面

 var files = JArray.Parse(YourJSON);
 var recList = files.SelectTokens("$").ToList();
 foreach (JObject item in recList.Children())
  {
    foreach (JProperty prop in item.Children())
      {
         string key = prop.Name.ToString();
         string value = prop.Value.ToString();
        // and add these to an array
      }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM