【问题标题】:How do I deserialize a JSON array(flat) and ignore some token如何反序列化 JSON 数组(平面)并忽略某些令牌
【发布时间】:2017-08-30 11:34:27
【问题描述】:

我收到了来自服务器的响应

 [{
  "sys_id": "******************************",
  "dv_model_id": "*****************",
  "due": "YYYY-MM-DD HH:mm:ss",
  "assigned_to": "1524s32a54dss412s121s",
  "dv_assigned_to": "username",
  "assigned_to.phone": "+12345678910",
  "assigned_to.email": "abc@a.c",
  "u_borrower_id": "fb36e45f0a12452004742183457e833b0",
  "dv_u_borrower_id": "antoherUserName",
  "u_borrower_id.phone": "+12345678910",
  "u_borrower_id.email": "abcf@a.c"
}
,{....}
,{....}]

我正在尝试将其反序列化为 List

public class Inventory
{
    public Inventory()
    {
        assigned_to = new User();
        u_borrower_wwid = new User();
    }

    public string sys_ID { get; set; }
    public string dv_model_id { get; set; }
    public DateTime due { get; set; }
    public string dv_assigned_to { get; set; }
    public User assigned_to { get; set; }
    public string dv_u_borrower_id { get; set; }
    public User u_borrower_id { get; set; }
}

现在,因为 JSON 包含 - "assigned_to": "1524s32a54dss412s121s"," 反序列化失败。 与 - ""u_borrower_id": "fb36e45f0a12452004742183457e833b0"," 相同。

你知道有什么方法可以忽略它们吗?或从 JSON 中删除它们? 我只需要对象的属性(“.phone”和“.email”)。

有什么想法吗?

【问题讨论】:

    标签: c# json deserialization json-deserialization


    【解决方案1】:

    我看到了一些解决方案:


    修改您的 Inventory 对象(或创建一个新对象),以便可以完全反序列化 json,然后访问那里的值。

    您的新对象和更新后的对象应如下所示:

    public class InventoryJsonObject
    {
        public string sys_id { get; set; }
        public string dv_model_id { get; set; }
        public string due { get; set; }
        public string assigned_to { get; set; }
        public string dv_assigned_to { get; set; }
    
        [JsonProperty("assigned_to.phone")]
        public string assigned_to_phone { get; set; }
    
        [JsonProperty("assigned_to.email")]
        public string assigned_to_email { get; set; }
        public string u_borrower_id { get; set; }
        public string dv_u_borrower_id { get; set; }
    
        [JsonProperty("u_borrower_id.phone")]
        public string u_borrower_id_phone { get; set; }
    
        [JsonProperty("u_borrower_id.email")]
        public string u_borrower_id_email { get; set; }
    }
    

    使用正则表达式从字符串中获取值。在这种情况下,您的正则表达式将是 "u_borrower_id\.phone": "(.*?)""u_borrower_id\.email": "(.*?)"

    完整的正则表达式解决方案可能如下所示(假设每个对象都包含电话和电子邮件):

    string phonePattern = "\"u_borrower_id\\.phone\": \"(.*?)\"";
    string emailPattern = "\"u_borrower_id\\.email\": \"(.*?)\"";
    
    Regex phoneRegex = new Regex(phonePattern);
    var phoneMatches = phoneRegex.Matches(input);
    
    Regex emailRegex = new Regex(emailPattern);
    var emailMatches = emailRegex.Matches(input);
    
    for (int i = 0; i < phoneMatches.Count; i++)
    {
        string phoneMatch = phoneMatches[i].Groups[1].Value;
        string emailMatch = emailMatches[i].Groups[1].Value;
        // Now you can add them to any collection you desire
    }
    

    stringUser 之间实现转换。 由于您的错误源于字符串fb36e45f0a12452004742183457e833b0 不能简单地转换为User 对象这一事实,因此您必须实现演员。它看起来像这样:

    public static implicit operator User(string _string)
    {
        // This could be a DB lookup, or basically anything else
        return new User()
        {
            id = _string
        };
    }
    

    【讨论】:

    • 好的,但我应该如何忽略平面信息? (u_borrower_id) 抛出异常Could not cast or convert from System.String to Models.User.Error converting value "755231490a12165100163a8b96a688b9" to type 'Models.User'. Path '[0].assigned_to', line 1, position 536.
    • 创建一个名为u_borrower_idassigned_to 的新模型是字符串,而不是Users。
    • @danielziv 您收到错误是因为序列化程序正在尝试将字符串“用户名”和“fb36e45f0a12452004742183457e833b0”转换为User 类型的对象。
    • 所以基本上我需要将对象展平然后将其解析回库存对象?
    • @danielziv 是的,这是一种解决方案,您还可以在字符串和用户之间实现强制转换(这可能是最干净的)。查看我刚刚进行的编辑。
    【解决方案2】:

    为了避免导致错误的不必要的转换,您可以通过创建Dictionary&lt;string, object&gt; 来使用此解决方法 只读取您需要的属性作为字符串并将它们转换为您想要的类型:

    using System.Web.Script;
    
    Dictionary<string, object> dict = Serialization.JavaScriptSerializer().Deserialize<Dictionary<string, object>>(json);
    

    现在您可以一一修改您的类属性,例如: (您可以为 DateTime 和 User 属性创建其他方法)

    Inventory inventory = new Inventory();
    
    //notice i'v added the 'u_borrower_id_email' property to your class:
    inventory.u_borrower_id_email = dict.GetStringOrDefault("u_borrower_id.phone");
    
    private static string GetStringOrDefault(this Dictionary<string, object> data, string key)
    {
        string result = "";
        object o;
        if (data.TryGetValue(key, out o))
        {
            if (o != null)
            {
                result = o.ToString();
            }
        }
        return result;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-24
      • 2020-09-16
      • 1970-01-01
      • 1970-01-01
      • 2015-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多