当反序列化以下json响应时,我设法获得订阅者ID,电子邮件和状态,这很容易,因为这些名称始终相同并且不依赖于列表中的特定设置。但是,如何将合并字段和在不同列表中具有不同名称的兴趣反序列化?
{ "members": [ {
"id": "f777bbffab8d1ceca8b757df63c47cb8",
"email_address": "urist.mcvankab+1@freddiesjokes.co",
"unique_email_id": "882e9bec19",
"status": "subscribed",
"merge_fields":{
"FNAME": "",
"LNAME": "" },
"interests":{
"9143cf3bd1": true,
"3a2a927344": false,
"f9c8f5f0ff": false,
"f231b09abc": true,
"bd6e66465f": false },
//And so on...
如何更改我的类以反序列化响应?
我的会员班
public class Member
{
public string id { get; set; }
public string email_address { get; set; }
public string status { get; set; }
//public List<MergeField> mergeFields { get; set; }
//public List<Interests> interests { get; set; }
}
MergeField引用我的旧MergeField类,其中字段是硬编码的
public class MergeField
{
public string FNAME { get; set; }
public string LNAME { get; set; }
public string ADDRESS { get; set; }
public string MERGE4 { get; set; }
}
但我想在请求列表的合并字段时使用相同的两个Mergefield(s)类来反序列化json响应。
public class MergeFields
{
public List<Mergefield> merge_fields { get; set; }
public string list_id { get; set; }
public int total_items { get; set; }
}
public class Mergefield
{
public string merge_id { get; set; }
public string tag { get; set; }
public string name { get; set; }
public string list_id { get; set; }
}
我找到了这个答案How do deserialize JSON with non-standard (and varying) property names,但我无法弄清楚如何在我的场景中使用它。
答案 0 :(得分:2)
您可以对合并字段使用Dictionary<string, object>
类型,为感兴趣使用Dictionary<string, bool>
类型。这是Member
课程应该是什么样子
public class Member
{
public string id { get; set; }
public string email_address { get; set; }
public string status { get; set; }
public Dictionary<string, object> merge_fields { get; set; }
public Dictionary<string, bool> interests { get; set; }
}
假设您正在使用MemberResponse
类作为响应,如下所示
public class MemberResponse
{
public List<Member> members { get; set; }
public string list_id { get; set; }
public int total_items { get; set; }
}
以下是获取每个合并字段和兴趣值的方法
MemberResponse memberResponse = .... // your code that calls the API
// enumerate members
foreach (var member in memberResponse.members)
{
// enumerate merge fields
foreach (var key in member.merge_fields.Keys)
{
// when key = "FNAME", value would be the first name of the member
// when key = "LNAME", value would be the last name of the member
string value = member.merge_fields[key].ToString();
}
// enumerate interests
foreach (var key in member.interests.Keys)
{
// when key = "9143cf3bd1", value would be true
// when key = "3a2a927344", value would be false
// ... and so on
bool value = member.interests[key];
}
}
很遗憾没有办法使用name
端点获取合并字段的merge_id
和/lists/{list_id}/members
,因为响应正文只包含tag
的{{1}}合并字段,即FNAME
,LNAME
等。您需要单独调用/lists/{list_id}/merge-fields
端点并比较每个合并字段的tag
获取相关的name
和merge_id
。