Reputation: 1998
I have a JSON
{{ "action": "rma", "devices": "[95001105,30013103,300117]", "devandreason": [ { "device": 95001105, "reason": 100 }, { "device": 30013103, "reason": 300 }, { "device": 300117, "reason": 200 } ]}}
for which I'm trying to get the devandreason
as an array.
I've tried creating classes
public class DevReasonList
{
public List<DevReason> devandreason { get; set; }
}
public class DevReason
{
public Double device { get; set; }
public Double reason { get; set; }
}
and the json_serializer
:
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
DevReasonList deviceAndReasonList = json_serializer.Deserialize<DevReasonList>(json.devandreason);
but it throws an exception:
json_serializer.Deserialize<DevReasonList>(json.devandreason) 'json_serializer.Deserialize<DevReasonList>(json.devandreason)' threw an exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' dynamic {Microsoft.CSharp.RuntimeBinder.RuntimeBinderException}
But I don't know what I'm doing wrong :(
It is possible to deserialize devandreason
and make it an array?
Upvotes: 2
Views: 121
Reputation: 1764
This should be your model according to
public class Devandreason
{
public int device { get; set; }
public int reason { get; set; }
}
public class RootObject
{
public string action { get; set; }
public string devices { get; set; }
public List<Devandreason> devandreason { get; set; }
}
I removed the beginning { and trailing } and it now validates
{ "action": "rma", "devices": "[95001105,30013103,300117]", "devandreason": [ { "device": 95001105, "reason": 100 }, { "device": 30013103, "reason": 300 }, { "device": 300117, "reason": 200 } ]}
Bonus: http://json2csharp.com/
Edit: As raised by @Sven in the comments: RootObject would be so much easier to traverse if your devices type was List.
Here is the json that would be required, I just removed the quotes before the value:
{ "action": "rma", "devices": [95001105,30013103,300117], "devandreason": [ { "device": 95001105, "reason": 100 }, { "device": 30013103, "reason": 300 }, { "device": 300117, "reason": 200 } ]}
Upvotes: 5