将json字符串转换为.net对象数组

本文关键字:net 对象 数组 转换 json 字符串 | 更新日期: 2023-09-27 18:29:47

我正在尝试转换json字符串(内容)响应

使用解析为Attachment[]对象

Attachment attachment = JsonConvert.DeserializeObject<Attachment>(content);

问题:如何将其转换为Attachment[]对象数组?

将json字符串转换为.net对象数组

您的Attachment对象不能完全反映响应的数据结构。创建AttachmentCollection以包含附件数组:

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

然后反序列化为AttachmentCollection:

var attachments = JsonConvert.DeserializeObject<AttachmentCollection>(content);

您也可以使用list(Collection)来实现这一点。

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

您可以使用JSON.Net

您需要做的是首先获取JSONArray,并为JSON数组中的每个JSONObject执行for语句。在for语句中,可以使用Linq创建自定义Attachment类的列表。见下文:

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