2

I am new to C#, and did not find an easy piece of code to read a response from a URL. Example:

http://www.somesitehere.com/mysearch

The response is something like this ( I do not know what kind of response is this):

{ "response": {
"status": {
  "code": "0",
  "message": "Success",
  "version": "4.2"
},
  "start": 0,
  "total": 121,
  "images": [
    {
      "url": "www.someimagelinkhere.com/pic.jpg",
      "license": {
        "url": "",
        "attribution": "",
        "type": "unknown"
      }
    }
  ]
}}

After that I will to save that url "www.someimagelinkhere.com/pic.jpg" to a file. But this I know how to do. I just want to separate the url from the rest.

I saw this topic: Easiest way to read from a URL into a string in .NET

bye

Community
  • 1
  • 1
MatheusLPS
  • 65
  • 1
  • 7
  • possible duplicate of [Easiest way to read from a URL into a string in .NET](http://stackoverflow.com/questions/1048199/easiest-way-to-read-from-a-url-into-a-string-in-net) – Jwosty Jul 29 '13 at 19:21
  • What's wrong with the solution? The page you're fetching just seems to be in JSON format... – Jwosty Jul 29 '13 at 19:22
  • Link to [Json.NET](http://json.codeplex.com/). For future reference, you should look at the `Content-Type` header, which will usually tell you what the response type is. For example, this one might be something like `application/json`. – Jim Mischel Jul 29 '13 at 21:08

2 Answers2

3

Your response is of JSON Format. Use a library (NewtonSoft but there are others too) to extract the node you want.

Venkata Krishna
  • 14,926
  • 5
  • 42
  • 56
1

You can use something like JSON.NET by Newton soft, which can be found and installed using NuGet Package Manager in Visual Studio.

Also you could just do this.

var jSerializer = new JavaScriptSerializer();
var result = jSerializer.DeserializeObject("YOUR JSON RESPONSE STRING");

The JSON string will not be a C# object with properties that match your names such as start, total, images, etc. If you need to you can create a strong type object and cast your converted object to that one for ease of use.

Strong typed version:

var jSerializer = new JavaScriptSerializer();
var result = (YourStrongType)jSerializer.DeserializeObject("YOUR JSON RESPONSE STRING");

var imgUrl = result.images[0].url;
Cubicle.Jockey
  • 3,288
  • 1
  • 19
  • 31