Reputation: 93
I'm having trouble deserialising a JSON string into an object using JSON.net.
I'm calling the serialisation with:
Payload payload = JsonConvert.DeserializeObject<Payload>(string);
However, the resulting Payload
object is null
. Any ideas why?
My class:
public class Payload
{
public Payload()
{ }
public string Action { get; set; }
public Payload.Bill[] Bills { get; set; }
public string ResourceType { get; set; }
public string Signature { get; set; }
public class Bill
{
public Bill()
{ }
public string Amount { get; set; }
public string Id { get; set; }
public string MerchantId { get; set; }
public DateTimeOffset? PaidAt { get; set; }
public string SourceId { get; set; }
public string SourceType { get; set; }
public string Status { get; set; }
public string Uri { get; set; }
public string UserId { get; set; }
}
}
My JSON string:
{
"payload": {
"bills": [
{
"id": "xxxx",
"status": "withdrawn",
"uri": "xxxx",
"amount": "5.19",
"amount_minus_fees": "5.14",
"source_type": "subscription",
"source_id": "xxx",
"payout_id": "xxx"
}
],
"resource_type": "bill",
"action": "withdrawn",
"signature": "xxx"
}
}
Upvotes: 0
Views: 1088
Reputation: 1
try below one
The type parameter for DeserializeObject has to be List<Payload>
instead of string. it would be JsonConvert.DeserializeObject<List<Payload>>(json)
.
Upvotes: -1
Reputation: 5299
The resulting payload object is null because the json string structure does not match with your Payload
class. You need additional wrapper class to deserialize it successfully:
public class PayloadWrapper
{
public PayloadWrapper()
{
Payload = new Payload();
}
public Payload Payload { get; set; }
}
and the deserialization logic:
PayloadWrapper wrap = JsonConvert.DeserializeObject<PayloadWrapper>(jsonStr);
To avoid creating another wrapper class, you can use LINQ to JSON:
JObject obj = JObject.Parse(jsonStr);
Payload payload = obj["payload"].ToObject<Payload>();
where jsonStr
variable is the json string you posted. Also I noticed that some of the properties in the json string do not match with the property names of the Payload
class, like resource_type
in the json string and ResourceType
in the class. Add JsonProperty
attribute to them for successful deserialization.
Upvotes: 3