将JSON树结构转换为列表

时间:2018-01-09 11:54:35

标签: c# asp.net json json.net

我是JSON的新手。我在树结构中有一个JSON列表,如下所示:

{
  "complaint@simulator.amazonses.com": {
    "time": "2018-01-02T20:45:46.65Z",
    "type": "Complaint",
    "bounceType": "null",
    "bounceSubType": "null"
  },
  "struax@example.org": {
    "time": "2018-01-02T20:53:03Z",
    "type": "Bounce",
    "bounceType": "Permanent",
    "bounceSubType": "Suppressed"
  },
  "bounce-test@service.socketlabs.com": {
    "time": "2018-01-02T21:06:40.097Z",
    "type": "Bounce",
    "bounceType": "Permanent",
    "bounceSubType": "Suppressed"
  },
  "bounce@simulator.amazonses.com": {
    "time": "2018-01-02T21:08:02Z",
    "type": "Bounce",
    "bounceType": "Permanent",
    "bounceSubType": "General"
  },
  "jstrechay@example.org": {
    "time": "2018-01-05T06:31:39Z",
    "type": "Bounce",
    "bounceType": "Permanent",
    "bounceSubType": "General"
  },
  "leematt45@example.org": {
    "time": "2018-01-05T06:49:13Z",
    "type": "Bounce",
    "bounceType": "Permanent",
    "bounceSubType": "Suppressed"
  },
  "afbweb@example.org": {
    "time": "2018-01-07T12:50:38Z",
    "type": "Bounce",
    "bounceType": "Transient",
    "bounceSubType": "General"
  },
  "bajanina2013@example.org": {
    "time": "2018-01-02T08:12:19Z",
    "type": "Bounce",
    "bounceType": "Transient",
    "bounceSubType": "MailboxFull"
  },
  "martin.bunt@example.org": {
    "time": "2018-01-05T07:00:24Z",
    "type": "Complaint",
    "bounceType": "null",
    "bounceSubType": "null"
  }
}

我的SQL表格列为EmailtimetypebounceTypebounceSubType。 如何从JSON列表中提取数据并将其保存在DB中?

我正在使用此代码:

string JSON = response.Content.ReadAsStringAsync().Result;
var jObj = (JObject)JsonConvert.DeserializeObject(JSON);

JSON采用树形结构,我无法获取父节点和列表中的相应子节点。

3 个答案:

答案 0 :(得分:1)

如果您使用 c#.NET ,使用 Json.NET 或使用 Newtonsoft.Json.Linq 非常简单。

第一种方法:

dynamic jsonObject = JsonConvert.DeserializeObject("your json string");

第二种方法:

dynamic jsonObject = JObject.Parse("your json string");

解析后,您可以将 jsonObject 传递给数据库。

答案 1 :(得分:1)

您需要根据Json响应创建一个类。而不是从那个类反序列化您的对象像这样

Class1 class1Object = JsonConvert.DeserializeObject<Class1>(str)

答案 2 :(得分:0)

这是我要做的。首先,定义一个模型类来保存项目数据(您可能已经有这样的类):

class BounceItem
{
    public string Email { get; set; }
    public DateTime Time { get; set; }
    public string Type { get; set; }
    public string BounceType { get; set; }
    public string BounceSubType { get; set; }
}

接下来,将JSON反序列化为Dictionary<string, BounceItem>

var dict = JsonConvert.DeserializeObject<Dictionary<string, BounceItem>>(json);

电子邮件地址将成为字典中的键,值将是包含嵌套属性的BounceItem个对象。但请注意,此时不会填充每个Email中的BounceItem属性。

要解决此问题,请对字典进行后期处理,以将每个密钥复制到相应项目的Email属性中,并将结果存储到List<BounceItem>

var list = dict.Select(kvp => { kvp.Value.Email = kvp.Key; return kvp.Value; }).ToList();

现在您有一个模型对象列表,它们应该与您的SQL表匹配,您可以使用适合您所选数据库的任何方法插入它们。

小提琴:https://dotnetfiddle.net/5rzyCs