基于另一个值在JSON数组中获取值的最简单方法是什么?

时间:2018-08-28 08:44:32

标签: json vb.net json.net

这是我的JSON:

{
"contacts": [{
    "identity-profiles": [{
        "identities": [{
            "type": "EMAIL",
            "value": "twitterman@twitter.com",
            "timestamp": 1531322937327,
            "is-primary": true
        }, {
            "type": "LEAD_GUID",
            "value": "10000-10000-10000-10000",
            "timestamp": 1531322937344
        }]
    }],
},
}

我想获取类型=“ Email”的值。我的问题是,它可能显示如下,因此它的顺序并不总是与上面相同:

{
"contacts": [{
    "identity-profiles": [{
        "identities": [{
            "type": "LEAD_GUID",
            "value": "10000-10000-10000-10000",
            "timestamp": 1531322937344              
        }, {
            "type": "EMAIL",
            "value": "twitterman@twitter.com",
            "timestamp": 1531322937327,
            "is-primary": true
        }]
    }],
},
}

这是当前的VB代码,仅提供JSON数组中第一个出现的值:

For Each item In jcontacts.ToList()
    Dim portalId = item("portal-id").ToString()
    Dim associatedCompanyId = If(item("properties")("associatedcompanyid")?("value").ToString, DBNull.Value)
    Dim contactId = item("vid").ToString()
    Dim firstName = If(item("properties")("firstname")?("value").ToString(), DBNull.Value)
    Dim lastName = If(item("properties")("lastname")?("value").ToString(), DBNull.Value)
    Dim email = If(item("identity-profiles")(0)("identities")?("value").ToString(), DBNull.Value)
    Dim telephone = If(item("properties")("phone")?("value").ToString(), DBNull.Value)
    Dim createDate = If(item("addedAt").ToString(), DBNull.Value)
    Dim modifiedDate = If(item("properties")("lastmodifieddate")?("value").ToString(), DBNull.Value)
Next

谢谢。

1 个答案:

答案 0 :(得分:1)

感谢@ADyson向我指出了正确的方向。现在是我的循环:

For Each item In jcontacts.ToList()
    Dim portalId = item("portal-id").ToString()
    Dim associatedCompanyId = If(item("properties")("associatedcompanyid")?("value").ToString, DBNull.Value)
    Dim contactId = item("vid").ToString()
    Dim firstName = If(item("properties")("firstname")?("value").ToString(), DBNull.Value)
    Dim lastName = If(item("properties")("lastname")?("value").ToString(), DBNull.Value)
    Dim email = Nothing
    Dim profile = item("identity-profiles")(0)("identities")
    For Each sitem In profile
        If (sitem("type").ToString() = "EMAIL") Then
            email = sitem("value").ToString()
            Exit For
        Else
            email = DBNull.Value
        End If
        Next
    Dim telephone = If(item("properties")("phone")?("value").ToString(), DBNull.Value)
    Dim createDate = If(item("addedAt").ToString(), DBNull.Value)
    Dim modifiedDate = If(item("properties")("lastmodifieddate")?("value").ToString(), DBNull.Value)
Next