How to deserialize to an object of this type using NewtonSoft JSON? The structure contains the property type variable, but with the use of NewtonSoft based on this structure, this property would be another class.
The following code example:
public class RootProduct
{
public Package Package {get; set;}
}
public class Package
{
//Package has a property in which the class type should be changed in order to deserialize
public Package_id ThisValueIsVariable {get; set;}
}
public class Package_id
{
public string product_name {get; set;}
}
In the data query of this package it is necessary to send the Package_id, the return of this query is received as in the structure below, the field "Package_id" (in return JSON) is this code sent in the query.
Returned JSON:
"Package": {
"Package_id": { //This is the value that changes according to the value passed in the query to JSON
"package_name": "my product name"
}
}
"Package": {
"SecondPackage_id": { //This is the value that changes according to the value passed in the query to JSON
"package_name": "my product name"
}
}
"Package": {
"ThirdPackage_id": { //This is the value that changes according to the value passed in the query to JSON
"package_name": "my product name"
}
}
UPDATE:
In the above code only the first product will be deserialized, because there is only one class with the name "package_id", and the second and third JSON items will not deserialize using JsonConvert.Deserialize because the SecondPackage_id class does not exist Consecutively.
The solution depends if you know the name before runtime or not.
When you know the possible names before hand you can create a separate property for each type in the Package class as follows:
public class Package
{
public Package_id FirstPackage {get; set;}
public Package_id SecondPackage {get; set;}
public Package_id ThridPackage {get; set;}
}
Other properties should reserialize to null.
When you do not know the possible ids at runtime then you are actually receiving a key value pair. Because they key is different per object, there technically could be multiple (even if in you case it might only always be one). Use a dictionary to get (multiple) named objects from JSON
public class RootProduct
{
//No package class needed
public IDictionary<string, Package_id> Package {get; set;}
}
public class Package_id
{
public string product_name {get; set;}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments