This is just a quick addendum to a colleague's post about using JSON in .NET.

Original post

See Dan's post here: Google Translate and .NET (Dan Matthews)

Complete example code

This example translates the phrase "a piece of pie" into French using Google Translate.  I do not use any processing on the JSON output except to convert it into an XML document that can be processed in .NET:

using System;
using System.Net;
using System.Web;
using System.IO;
using System.Xml;
using System.Runtime.Serialization.Json;

namespace JSON_Example
{
    class Program
    {
        static void Main(string[] args)
        {
            WebRequest req = WebRequest.Create(
                "http://ajax.googleapis.com/ajax/" +
                "services/language/translate?v=1.0&q=" + 
                HttpUtility.UrlEncode("a piece of pie") + 
                "&langpair=" + "en" + "%7C" + "fr");
            WebResponse res = req.GetResponse();


            XmlDocument doc = new XmlDocument();
            using (Stream s = res.GetResponseStream())
            {
                XmlDictionaryReader xr = 
                    JsonReaderWriterFactory.CreateJsonReader(
                        s,
                        XmlDictionaryReaderQuotas.Max);

                doc.Load(xr);
                xr.Close();
                s.Close();
            }
            Console.WriteLine(doc.OuterXml);

            Console.ReadKey();
        }
    }
}

Required assemblies

  • System.Runtime.Serialization (3.0)
  • System.ServiceModel.Web (3.5)
  • System.Web (2.0)
  • System.Xml (2.0)
  • and the other usual suspects

Versions

  • Microsoft .NET Framework 3.5

Metadata


Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist
posted @ Thursday, May 22, 2008 4:05 PM | in .NET Software Development

Comments

No comments posted yet.

Post Comment

Title *
Name *
Email
Url
Comment *  


Please add 6 and 4 and type the answer here: