我使用下面的代码反序列化了一个JsonResponse。
var data = (JObject)JsonConvert.DeserializeObject(jsonResponse);
我得到了响应字符串,看起来像这样
{
"results":[
{
"url":"tickets/2063.json",
"id":20794,
"subject":"Device not working",
"created_date": "2018-01-10T13:03:23Z",
"custom-fields":[
{
"id":25181002,
"value":34534
},
{
"id":2518164,
"value":252344
}
]
}
]
}
我的目标是读取此json对象数组中的某些字段并插入到数据库中。我需要的字段是id,subject,created_date,member_id。
成员ID是自定义字段的一部分。 member_id是id = 2518164的值。我用List来存储这个,如果List或Dictionary更适合这种情况,你能不能告诉我。如何实现字典
var data = (JObject)JsonConvert.DeserializeObject(jsonResponse);
var tickets = data["results"].ToList();
foreach (var ticketItem in tickets){
Int64? ticketFormId = ticketItem["id"].Value<Int64>();
string subject = ticketItem["subject"].Value<string>();
DateTime createdDate = ticketItem["created_date"].Value<DateTime>();
//Do you think for the next step a dictionary is better or a List is better, since I want to search for a particular id=2518164
var fieldsList = ticketItem["fields"].ToList();
foreach(var fieldItem in fieldList){
Int64? fieldId = fieldItem["id"].Value<Int64>();
if(fieldId!=null && fieldId == 2518164){
memberId = fieldItem["value"].Value<string>();
}
}
}
答案 0 :(得分:1)
如果您要将它们全部插入数据库,请将它们存储到列表中。字典仅对通过键搜索项目很有用。
您还可以使用linq以更简单的方式处理json:
var tickets = JObject.Parse(jsonResponse)["results"]
.Select(ticket => new
{
Id = (long)ticket["id"],
Subject = (string)ticket["subject"],
CreatedDate = (DateTime)ticket["created_date"],
MemberId = (long)ticket["custom-fields"]
.FirstOrDefault(cf => (int)cf["id"] == 2518164)
?["value"],
})
.ToList();