Reputation: 27
I am trying to convert a json string (content) response
to parse into Attachment [] object using
Attachment attachment = JsonConvert.DeserializeObject<Attachment>(content);
Question: How do I turn it into an Attachment [] object array?
Upvotes: 0
Views: 1245
Reputation: 8025
Your Attachment
object doesn't quite reflect the data structure of the response. Create an AttachmentCollection to contain the array of attachments:
public class AttachmentCollection
{
public List<Attachment> Attachment { get; set; }
}
Then deserialize as an AttachmentCollection
:
var attachments = JsonConvert.DeserializeObject<AttachmentCollection>(content);
Upvotes: 2
Reputation: 582
You could use JSON.Net
What you need to do is first get the JSONArray and do a for statement for each JSONObject in the JSON Array. In the for statement you could use Linq to create a list of your custom Attachement class. See below:
List<Attachment> AttachmentList = new List<Attachment>();
JArray a = JArray.Parse(jsonString);
foreach (JObject o in a.Children<JObject>())
{
Attachment newAttachment = new Attachment
{
WriteUpID = (int)o["WriteUpID"],
InitialScanID = (int)o["InitialScanID"],
//etc, do this for all Class items.
}
AttachmentList.Add(newAttachment);
}
//Then change the AttachmentList to an array when you're done adding Attachments
Attachment[] attachmentArray = AttachmentList.ToArray();
Voila
Upvotes: 0
Reputation: 1058
You can also use list(Collection) for that.
public class RootObject
{
public List<Attachment> Attachment { get; set; }
}
Upvotes: 0