【问题标题】:JSON.NET: getting json from external source with streams, how to get just one value?JSON.NET:使用流从外部源获取 json,如何只获取一个值?
【发布时间】:2016-11-04 09:44:45
【问题描述】:

我有以下代码:

static void Main(string[] args)
{
    HttpClient client = new HttpClient();

    using (Stream stream = client.GetStreamAsync("https://opendata.rdw.nl/resource/8ys7-d773.json?kenteken=61SFSL").Result)
    using (StreamReader streamReader = new StreamReader(stream))
    using (JsonReader reader = new JsonTextReader(streamReader))
    {
        JsonSerializer serializer = new JsonSerializer();

        // read the json from a stream
        // json size doesn't matter because only a small piece is read at a time from the HTTP request


        //What do I do here to get my one value?


    }

    Console.WriteLine("Press any key to continue...");
    Console.Read();
}

我是从 JSON.NET 网站上的文档中得到的。原因是我不想加载整个字符串,而是一块一块地加载。响应如下:

[{"brandstof_omschrijving":"Benzine","brandstof_volgnummer":"1","brandstofverbruik_buiten":"6.60","brandstofverbruik_gecombineerd":"8.20","brandstofverbruik_stad":"11.10","co2_uitstoot_gecombineerd":"196","emissiecode_omschrijving":"Euro 4","geluidsniveau_rijdend":"71","geluidsniveau_stationair":"82","kenteken":"61SFSL","milieuklasse_eg_goedkeuring_licht":"70/220*2001/100B","nettomaximumvermogen":"99.00","toerental_geluidsniveau":"4125"}]

即,它返回一个包含一个 json 对象的数组,我想使用流只检索其中的一个值。我该怎么做?

【问题讨论】:

  • 你给自己制造了很多问题。你基本上会重写一个解析器。
  • 好吧...那你有什么建议?
  • 您无法加载结果的任何特殊原因?是不是数据量比较大?
  • 您试图访问哪个值?
  • 不,据我所知,您不能请求多个对象的数组。我的问题中有一个关于数据外观的示例。够傻的,我只需要一个值。但简而言之,回答您的问题:不,这不是很多数据。在字符串中,我正在尝试使用键“co2_uitstoot_gecombineerd”获取值

标签: json c#-4.0 json.net


【解决方案1】:

你可以试试下面的

using System;
using System.Net.Http;
using Newtonsoft;

public class Program {

    public static void Main() {
        var client = new HttpClient();
        var json = client.GetStringAsync("https://opendata.rdw.nl/resource/8ys7-d773.json?kenteken=61SFSL").Result;
        var data = JsonConvert.DeserializeObject<dynamic>(json);
        string value = data[0].co2_uitstoot_gecombineerd;
        Console.WriteLine(value);
        Console.WriteLine("Press any key to continue...");
        Console.Read();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 2023-04-01
    相关资源
    最近更新 更多