Garth Marenghi Garth Marenghi - 9 months ago 44
JSON Question

JSON.NET: getting json from external source with streams, how to get just one value?

I have the following code:

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

using (Stream stream = client.GetStreamAsync("").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...");

I got this from the documentation over at the JSON.NET website. The reason being that I don't want to load the whole string, but piece by piece. The response is as follows:

[{"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"}]

I.e., it returns an array with one json object, and I want to retrieve just one value in there, using a stream. How might I do this?

Answer Source

You could try the following

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

public class Program {

    public static void Main() {
        var client = new HttpClient();
        var json = client.GetStringAsync("").Result;
        var data = JsonConvert.DeserializeObject<dynamic>(json);
        string value = data[0].co2_uitstoot_gecombineerd;
        Console.WriteLine("Press any key to continue...");