我从服务中获得了以下JSON。
查看三个记录的样本:
{"[email protected]":[{"action":"open","timestamp":"2018-09-05 20:46:00","url":null,"ip":"66.102.6.98"}]}
{"[email protected]":[{"action":"open","timestamp":"2018-09-05 18:01:29","url":null,"ip":"66.102.8.129"}]}
{"[email protected]":[{"action":"open","timestamp":"2018-09-05 15:08:26","url":null,"ip":"66.102.6.109"}]}
第一个键总是在变化,那么将它转换为.NET对象的最佳方法是什么?
当它的密钥不同时,我不确定是否还有其他方法可以反序列化json。当密钥不同时,它被认为是另一种类型。您可以使用正则表达式剥离Json的常量部分并对其进行反序列化。
试试这是否有帮助
public class CommonPart
{
[JsonProperty("action")]
public string action { get; set; }
[JsonProperty("timestamp")]
public string timestamp { get; set; }
[JsonProperty("url")]
public object url { get; set; }
[JsonProperty("ip")]
public string ip { get; set; }
}
public class EmailPart
{
public string Email { get; set; }
public IList<CommonPart> Model { get; set; }
}
然后使用方法获取如下所示的json
public EmailPart GetFromJson(string json)
{
var pattern = @"\[(.*?)\]";
var regex = new Regex(pattern);
var response = regex.Match(json);
var test1GmailCom = response.Value;
var responseModel = JsonConvert.DeserializeObject<List<CommonPart>>(test1GmailCom);
var ex = new EmailPart();
ex.Model = responseModel;
var pattern2 = @"\'(.*?)\'";
var regex2 = new Regex(pattern2);
var email = regex2.Match(json).Value.Replace("'", string.Empty);
ex.Email = email;
return ex;
}
我不认为这是最好的方式。最好是你可以更新Json,可能如下
{“Data”:{“[email protected]”:[{“action”:“open”,“timestamp”:“2018-09-05 20:46:00”,“url”:null,“ip” :“66.102.6.98”}]}}
使用Cinchoo ETL(一个开源库),您可以将JSON加载到.NET对象,如下所示
.net对象定义
public class ActionMessage
{
public string Action { get; set; }
public DateTime Timestamp { get; set; }
public string Url { get; set; }
public string IP { get; set; }
}
JSON解析代码
string json = @"{
""[email protected]"": [
{
""action"": ""open"",
""timestamp"": ""2018-09-05 20:46:00"",
""url"": ""http://www.google.com"",
""ip"": ""66.102.6.98""
}
]
}";
using (var p = ChoJSONReader<ActionMessage>.LoadText(json)
.WithJSONPath("$.*")
)
{
foreach (var rec in p)
{
Console.WriteLine("action: " + rec.Action);
Console.WriteLine("timestamp: " + rec.Timestamp);
Console.WriteLine("url: " + rec.Url);
Console.WriteLine("ip: " + rec.IP);
}
}
输出:
action: open
timestamp: 9/5/2018 8:46:00 PM
url: http://www.google.com
ip: 66.102.6.98