简体   繁体   English

如何使用DataContractJsonSerializer使用从Web(以JSON形式)获取的数据设置对象属性的子集

[英]How to set a subset of properties of an object using data obtained from web (in form of JSON) using DataContractJsonSerializer

I am making a Travel app project consisting of a backend coded in PHP and a UWP app (frontend) coded in C#. 我正在制作一个旅行应用程序项目,包括用PHP编码的后端和用C#编码的UWP应用程序(前端)。

Following represent the "Holiday Package" class implemented in C# 以下代表用C#实现的“Holiday Package”类

 public class Packages
{
    public string PackageID { get; set; }
    public string Name { get; set; }
    public string Destination { get; set; }
    public string Description { get; set; }
    public int Duration { get; set; }
    public float BasePrice { get; set; }
    public List<string> Images { get; set; }

    public HotelInPackage Hotel { get; set; }

    public string TransportType { get; set; }

    public Packages(string packageID,string name,string destination,string description,int duration,float basePrice,List<string> images)
    {
        PackageID = packageID;
        Name = name;
        Destination = destination;
        Description = description;
        Duration = duration;
        BasePrice = basePrice;
        Images = images;
    }

    public void HotelConstruct(string hotelID,string name,int cat)
    {
        Hotel = new HotelInPackage(hotelID, name, cat);
    }

    public void SetTransport(string transportType)
    {
        TransportType = transportType;
    }

    public void ChangeImageName()
    {
        int i = 0;
        while(i<Images.Count)
        {
            Images[i] = string.Format("Assets/CitiesPlaceholder/{0}.jpg",Images[i]);
            i++;
        }
    }
}

Following is the JSON string returned by the backend 以下是后端返回的JSON字符串

{
"PackageID":"P280",
"Name":"Sigapore Dreams",
"Destination":"Singapore",
"Description":"lorem ipsum,dolor sit amet",
"Duration":5,
"BasePrice":999.2
}

I want to deserialize the above JSON string into the "Packages" class thereby setting its "PackageID", "Name", "Destination", "Description", "Duration" and "BasePrice" properties ie I want to set only a subset of properties using web data 我想将上面的JSON字符串反序列化为“Packages”类,从而设置其“PackageID”,“Name”,“Destination”,“Description”,“Duration”和“BasePrice”属性,即我只想设置一个子集使用网络数据的属性

How to implement the above solution using the DataContractJsonSerializer class? 如何使用DataContractJsonSerializer类实现上述解决方案?

Do I need to Add/Modify any Constructor? 我是否需要添加/修改任何构造函数?

DataContractJsonSerializer will never call a parameterized constructor. DataContractJsonSerializer永远不会调用参数化构造函数。 Thus, as it stands, since your Packages type lacks a parameterless constructor, it throws an exception because it does not know how to construct an instance of such a type. 因此,就目前而言,由于您的Packages类型缺少无参数构造函数,因此它会抛出异常,因为它不知道如何构造这种类型的实例。

You have two ways to enble DataContractJsonSerializer to construct your object. 您有两种方法可以使用DataContractJsonSerializer构建对象。 Firstly, you can add a parameterless constructor. 首先,您可以添加无参数构造函数。 It could even be private: 它甚至可以是私人的:

public class Packages
{
    public string PackageID { get; set; }
    public string Name { get; set; }
    public string Destination { get; set; }
    public string Description { get; set; }
    public int Duration { get; set; }
    public float BasePrice { get; set; }
    public List<string> Images { get; set; }

    public HotelInPackage Hotel { get; set; }

    public string TransportType { get; set; }

    Packages()
    {
        Debug.WriteLine("Calling private constructor of " + GetType().FullName);
    }

    public Packages(string packageID, string name, string destination, string description, int duration, float basePrice, List<string> images)
    {
        PackageID = packageID;
        Name = name;
        Destination = destination;
        Description = description;
        Duration = duration;
        BasePrice = basePrice;
        Images = images;
    }
}

Alternatively, if you don't want even a private parameterless constructor, you can mark your type with [DataContract] and [DataMember] attributes: 或者,如果您不想要私有无参数构造函数,则可以使用[DataContract][DataMember]属性标记您的类型:

[DataContract]
public class Packages
{
    [DataMember]
    public string PackageID { get; set; }
    [DataMember]
    public string Name { get; set; }
    [DataMember]
    public string Destination { get; set; }
    [DataMember]
    public string Description { get; set; }
    [DataMember]
    public int Duration { get; set; }
    [DataMember]
    public float BasePrice { get; set; }
    [DataMember]
    public List<string> Images { get; set; }

    [DataMember]
    public HotelInPackage Hotel { get; set; }

    [DataMember]
    public string TransportType { get; set; }

    public Packages(string packageID, string name, string destination, string description, int duration, float basePrice, List<string> images)
    {
        PackageID = packageID;
        Name = name;
        Destination = destination;
        Description = description;
        Duration = duration;
        BasePrice = basePrice;
        Images = images;
    }
}

This works because, for data contract types, the data contract serializer does not call any constructor at all . 这是有效的,因为对于数据协定类型,数据协定序列化程序根本不会调用任何构造函数

Having implemented either of these options for Packages (and, probably, HotelInPackage , which is not included in the question), you can now deserialize your JSON. 已经为Packages实现了这些选项之一(可能HotelInPackage ,这个问题没有包含在内),您现在可以反序列化您的JSON。 Only those properties actually present in the JSON will be set. 只会设置JSON中实际存在的那些属性。

暂无
暂无

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

相关问题 使用DataContractJsonSerializer设置JSON对象root - Set JSON object root using DataContractJsonSerializer 使用DataContractJsonSerializer从JSON数据填充对象数组时出错 - Error filling an object array from JSON data using DataContractJsonSerializer 如何使用JSON.NET或DataContractJsonSerializer反序列化未类型化的对象 - How to deserialize an untyped object using JSON.NET or DataContractJsonSerializer 如何使用DataContractJsonSerializer解析具有可变键名的json对象 - How to parse json object with variable key names using DataContractJsonSerializer 无法使用DataContractJsonSerializer将对象序列化为JSON - Unable to Serialize Object to JSON Using DataContractJsonSerializer 使用DataContractJsonSerializer作为JSON数组序列化对象 - Serialize an object using DataContractJsonSerializer as a json array 使用 DataContractJsonSerializer 将字典序列化为 JSON 对象 - Serialize a Dictionary as JSON object using DataContractJsonSerializer 在C#中使用DataContractJsonSerializer反序列化JSON对象 - Deserialization of JSON object by using DataContractJsonSerializer in C# 使用DataContractJsonSerializer对JSON对象进行部分反序列化 - Partial deserialization of JSON object by using DataContractJsonSerializer 使用DataContractJsonSerializer,将JSON字符串反序列化为具有列表和接口作为属性的C#对象 - Using DataContractJsonSerializer, deserialization of JSON string into C# object which has list & interface as properties
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM