user2180842
user2180842

Reputation: 27

Convert json string to .net object array

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

Answers (3)

John Hoerr
John Hoerr

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

Ryan C
Ryan C

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

Dhru &#39;soni
Dhru &#39;soni

Reputation: 1058

You can also use list(Collection) for that.

public class RootObject
{
    public List<Attachment> Attachment { get; set; }
}

Upvotes: 0

Related Questions