Hey i would like to deserialize my json i get from a webrequest.
The problem ive got is that i have the same lable "id" I need to get the ID from the attachment and the id from the Source. Both got the name "id"
my json looks like this:
"data": [{
"id": 45,
"file_name": "test.pdf",
"description": "",
"attach_date": "2017-11-23T12:18:18Z",
"source": {
"id": 62,
"source_type": "features"
},
"created_by": {
"id": 100,
"user_type": 0
}
my code dont work cause i use the same lable in json property "id"
my class looks like:
public class Attachment
{
[JsonProperty("id")] public int AttachmentId { get; set; }
[JsonProperty("file_name")] public string FileName { get; set; }
[JsonProperty("id")] public int SourceId { get; set; }
}
is there a way i could change the json property to get the id from source:?
Sorry in advance im still a beginner in programming.
CodePudding user response:
I assume SourceId in your Attachment class is the id of source object in Your response. In such case You should create another class to represent the source
public class Attachment
{
[JsonProperty("id")] public int AttachmentId { get; set; }
[JsonProperty("file_name")] public string FileName { get; set; }
[JsonProperty("source")] public SourceEntity Source { get; set; }
}
public class SourceEntity
{
[JsonProperty("source_type")] public string SourceType { get; set; }
[JsonProperty("id")] public int Id { get; set; }
}
If You still want to access SourceId in Attachment class you can add
public int SourceId { get => Source.Id; }
to Attachment class
CodePudding user response:
You should paste your code into a C# class generator like jsonutils.com and it will give you the set of classes that will ultimately become your deserialization structure.
This is what your JSON gives me ...
public class Source
{
public int id { get; set; }
public string source_type { get; set; }
}
public class CreatedBy
{
public int id { get; set; }
public int user_type { get; set; }
}
public class Data
{
public int id { get; set; }
public string file_name { get; set; }
public string description { get; set; }
public DateTime attach_date { get; set; }
public Source source { get; set; }
public CreatedBy created_by { get; set; }
}
public class YourClass
{
public IList<Data> data { get; set; }
}
It's just boiler plate so it will need some adjusting but it's a start for you.