1

So I’m Calling a Web API From a ASP.NET core application. Im using HttpClient and reading it in as a string but i want to read it as a JSON object. I'm aware that that you can read it as Generic class ReadAsAsync<Generic>(); However, the returning object is a massive JSON object and it would be to much work to write a Generic class for it. My question is how can i just read it as its JSON object ?

    public async Task<IActionResult>  SendRequest()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(" https://api.forecast.io/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // HTTP GET
            HttpResponseMessage response = await client.GetAsync("forecast/KEY/");
            if (response.IsSuccessStatusCode)
            {
                var forcast = await response.Content.ReadAsStringAsync();
                Console.WriteLine("{0}", forcast);
                // return Json( JSON ) ; 
            }
        }
        // return Json( JSON ) ; 
    }

I see Three types of response readers, can any of these become JSON objects ?

ReadAsByteArrayAsync, ReadAsStreamAsync, ReadAsStringAsync
Tseng
  • 61,549
  • 15
  • 193
  • 205
AJ_
  • 3,787
  • 10
  • 47
  • 82
  • 1
    Please clarify: Are you saying that `forecast/KEY/` is already returning JSON-formatted text, and you are trying to figure out how to pass it as JSON-formatted text back to the caller of the Action method? If so, see this related question: http://stackoverflow.com/questions/18409863/how-to-output-json-string-as-jsonresult-in-mvc4 – stephen.vakil Aug 29 '16 at 15:56
  • @stephen.vakil I'm trying to read it in as a JSON object, or i guess convert the string into a JSON object. – AJ_ Aug 29 '16 at 16:07
  • What does `JSON object` mean? Based on the commented-out code, it seems like you want your action to just return the JSON as is so that it can be used by the javascript caller, in which case use the code in the link I provided, which will take the string returned by forecast.io and return it as JSON. If you mean, you want to manipulate it as an object before returning, then see the answer below. – stephen.vakil Aug 29 '16 at 16:11
  • oh, i see now. Yeah that’s what i'm trying to do. So should it look like this [ return Json(forecast, "application/json") ] ? – AJ_ Aug 29 '16 at 16:18
  • Probably `return Content(forcast, "application/json")` – stephen.vakil Aug 29 '16 at 16:30
  • Yeah i tried that. I dont get any errors, but when i print the object to the console it comes up as [object object]. When i debug it server side. It shows as Content:"THE JSON STRING", ContentType:"application/json" [string], StatusCode:null [int?], Non-Public members: – AJ_ Aug 29 '16 at 16:33
  • @stephen.vakil So i don’t know if its actually getting converted to a JSON object. – AJ_ Aug 29 '16 at 16:34
  • @stephen.vakil Yeah it worked. Awesome thanks!!! Should i have you post the answer, i post the answer, delete my question ? – AJ_ Aug 29 '16 at 16:52

2 Answers2

0

Use Json.NET to convert the string to an object (and viceversa):

http://www.newtonsoft.com/json/help/html/Overload_Newtonsoft_Json_JsonConvert_DeserializeObject.htm

Victor Hurdugaci
  • 28,177
  • 5
  • 87
  • 103
0

You can try parsing your JSON payload as JObject which would essentially allow you to even use LINQ to JSON.

Sample code from here:

JObject o = JObject.Parse(@"{
   'CPU': 'Intel',
   'Drives': [
     'DVD read/writer',
     '500 gigabyte hard drive'
  ]
}");

string cpu = (string)o["CPU"];
// Intel

string firstDrive = (string)o["Drives"][0];
// DVD read/writer

IList<string> allDrives = o["Drives"].Select(t => (string)t).ToList();
// DVD read/writer
// 500 gigabyte hard drive

Technically this would be much more appropriate for your case where you dont want a POCO to represent your payload.

And Json.net 4.0+ would actually allow you to use a dynamic instance too:

dynamic jsonResponse = JsonConvert.DeserializeObject("{\"message\":\"Hi\"}");
jsonResponse.Works = true;
Console.WriteLine(jsonResponse.message); // Hi
Console.WriteLine(jsonResponse.Works); // True
Console.WriteLine(JsonConvert.SerializeObject(jsonResponse)); // {"message":"Hi","Works":true}
Assert.That(jsonResponse, Is.InstanceOf<dynamic>());
Assert.That(jsonResponse, Is.TypeOf<JObject>());

See more on this here

Community
  • 1
  • 1
Swagata Prateek
  • 1,076
  • 7
  • 15