如何从httplistener中的.json文件加载数据

时间:2014-05-30 23:49:55

标签: javascript json httplistener

我是WebService / JavaScript开发环境的新手。我有一个任务 - 当前我们的HttpListener代码服务于.js文件的localhost请求。我需要的是能够在HttpListener中放置json对象。

  • 从JSON文件(.json)接收值类型,对象和列表(或数组)并将JSON字符串转换为JavaScript对象
  • 将值类型,对象和列表发送到JavaScript
  • 将上述json数据输出到控制台

如果你可以分享任何想法/解决方案如何实现这将是很好的。

这是我们的代码目前使用.js - HttpListener.cs:

private static void Main()
{
var server = new HttpListener();
server.Prefixes.Add("http://localhost:80/");

server.Start();
Console.WriteLine("Listening...");

while (true)
{
   HttpListenerContext context = server.GetContext();
   HttpListenerResponse response = context.Response;

   string fileId = string.Empty;
   try
   {
   string page = Path.Combine(Directory.GetCurrentDirectory(), context.Request.Url.LocalPath.Replace("/", @"\").Substring(1));
    Console.WriteLine("Get request from {0}", page);

    if (!string.IsNullOrEmpty(page) && !page.EndsWith(".js"))
    {
        Console.WriteLine("file is not a .js file.");
        continue;
    }

      // Check requested file really exists

      // Get file id property from the query string.
      fileId = context.Request.QueryString["fileid"];

      string msg;
      using (var sr = new StreamReader(page))
      {
           msg = sr.ReadToEnd();
      }

      byte[] buffer = Encoding.UTF8.GetBytes(msg);
      response.ContentLength64 = buffer.Length;
      response.ContentType = "text/javascript";

      using (Stream st = response.OutputStream)
      {
           Console.WriteLine(buffer.Length);
           st.Write(buffer, 0, buffer.Length);
           context.Response.StatusCode = (int)HttpStatusCode.OK;
           context.Response.StatusDescription = "OK";
           Console.WriteLine("Request done:{0}", fileId);
      }
      catch { } // suppress any exceptions
      finally
      {
           context.Response.Close();
           Console.WriteLine("Response closed:{0}", fileId);
      }
}

}

Data.json的示例。但是我们不知道将会出现什么字段名称和数据类型。

[
  {
    "name": "George",
    "gender": "male",
    "age": "5 years"
  },
  {
    "name": "Nancy",
    "gender": "female",
    "age": "10 years"
  },
  {
    "name": "Alex",
    "gender": "male",
    "age": "3 years"
  },
  {
    "name": "Maximus",
    "gender": "male",
    "age": "7 years"
  } 
]

0 个答案:

没有答案