3

I have a simple class:

public class site
        {
            public string URL { get; set; }
        }

That exists within a http handler. Currently I am posting json to this handler and trying to deserialize it to get the URL out of the string. I am however having a problem with the deserialize part of it.

I have a string "jsonString" that has the json formatted like so:

[{"URL":"http://www.google.com/etc/"}]

Here is my code for the deserialize:

JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();

        string jsonString = String.Empty;

        HttpContext.Current.Request.InputStream.Position = 0;
        using (StreamReader inputStream = new StreamReader(HttpContext.Current.Request.InputStream))
        {
            jsonString = inputStream.ReadToEnd();
        }

        site currSite = new site();
        currSite = jsonSerializer.Deserialize<site>(jsonString);

        //set response types
        HttpContext.Current.Response.ContentType = "application/json";
        HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;


       //send response 
       HttpContext.Current.Response.Write(jsonSerializer.Serialize(currSite.URL));  

I am then trying to send a response using currSite.URL however it is failing. What am I missing here? I am reasonably confident it is at the deserialize part because if I send a response of jsonString instead of currSite.URL it will work.

BlueBird
  • 1,406
  • 4
  • 24
  • 35

2 Answers2

4

Your json string shows that it's an array, not a single entity. You should deserialize it as so:

var result = jsonSerializer.Deserialize<site[]>(jsonString);

And result[0].Url should contain what you are looking for.

Update

Adding sample code:

 string json = @"[{""URL"":""http://www.google.com/etc/""}]";

 JavaScriptSerializer js = new JavaScriptSerializer();
 var result = js.Deserialize<site[]>(json);
 Console.WriteLine(result[0].URL);

Prints: http://www.google.com/etc/

Icarus
  • 63,293
  • 14
  • 100
  • 115
  • This put me on the correct path, I ended up changing the json that was being posted to a single entity and my code works. – BlueBird Jan 04 '13 at 16:28
0

If you're simply trying to send back the URL as the response (just the string) there's no need to serialize the value. Just pass currSite.URL to the Write method.

Otherwise, I'm guessing you should serialize the whole currSite object for the response rather than just the URL. It all depends on what kind of response the caller is expecting (which you haven't specified).

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536