【问题标题】:ASP.NET Deserialize JSON with LINQ and loop through resultsASP.NET 使用 LINQ 反序列化 JSON 并遍历结果
【发布时间】:2016-10-05 12:16:04
【问题描述】:

我正在尝试反序列化一个 JSON 字符串,然后遍历它的结果。 我从这里开始:http://www.newtonsoft.com/json/help/html/QueryJsonLinq.htm

我想把它翻译成 VB.NET 版本,但是我遇到了各种各样的错误。 我尝试了几个翻译器都没有运气(例如http://converter.telerik.com/)。

JSON 字符串

{
    "responseHeader": {
        "status": 0,
        "QTime": 1,
        "params": {
            "sort": "title asc"
            "rows": "10"
        }
    },
    "response": {
        "numFound": 3,
        "start": 0,
        "docs": [{
            "title": "Amsterdam",
            "cityurl": "amsterdam"
        }, {
            "title": "London",
            "cityurl": "london"
        }, {
            "title": "New York",
            "cityurl": "new-york"
        }]
    }
}

首先我尝试反序列化 JSON:

Dim postTitles = From p In rss("channel")("item")DirectCast(p("title"), String)
'End of Statement Expected on `DirectCast(p("title"), String)`

然后我尝试遍历结果,但是我在下面尝试的两种方法都不起作用

For Each item As var In postTitles
    Log("title", item)
Next
'type 'var' is not defined

For Each (dim item In postTitles)
    Log("title", item)
Next
'Expression expected (on `dim`)

VB.NET 中执行此操作的正确代码是什么?

【问题讨论】:

    标签: asp.net json vb.net linq deserialization


    【解决方案1】:
    Dim data As JObject = JObject.Parse(json)
    
    Dim postTitles = From doc In data("response")("docs")
                     Select doc("title").Tostring()
    
    For Each item In postTitles
        Log("title", item)
    Next
    

    参考:Introduction to LINQ in Visual Basic

    【讨论】:

    • 谢谢!使用您的代码,我在部分doc("title") 上得到设计时错误Value of type 'Newtonsoft.Json.Linq.JToken' cannot be converted to 'String'.。我不得不把它改成doc("title").ToString,这有关系吗?它现在确实生成了正确的输出:)
    • @Flo,如果这解决了与您的问题相关的问题,您可以将其标记为答案。谢谢。
    猜你喜欢
    • 2020-07-11
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-27
    • 1970-01-01
    相关资源
    最近更新 更多