1. Open VS2013 to create a new C# window application, and pull out a label, two textboxes and a button on the form
Change the attribute name of the textbox above to txtWord, and change the attribute name of the testbox below to txtResult
2. We create a class to store the deserialized translation results. The category is called TransObj. The code is as follows:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BaiduTrans { public class TransObj { public string from { get; set; } public string to { get; set; } public List<TransResult> trans_result { get; set; } } public class TransResult { public string src { get; set; } public string dst { get; set; } } }For deserialization of Json, we use Newtonsoft.Json. Install Newtonsoft.json with NuGet
Open the tool of vs2013 - NuGet Package Manager - Package Manager Console, then the command line appears in the bottom window of VS: pm>
Enter the command line:
pm> install-package newtonsoft.jsonPress Enter, and after a while, it will prompt that newtonsoft.json has been installed successfully.
3. Double-click the translate button and add the following code:
<span style="color:#444444;">using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Input; using Newtonsoft.Json; using System.Net; using System.IO; using System.Windows.Forms; namespace BaiduApi { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { WebClient client = new WebClient(); string txtInput = txtWord.Text; txtInput = txtInput.Replace(@"#", "%23"); string url = string.Format("http://openapi.baidu.com/public/2.0/bmt/translate?client_id=</span><span style="color:#ff6666;">YourApiKey</span><span style="color:#444444;">&q={0}&from=auto&to=auto", txtInput); var buffer = client.DownloadData(url); string result = Encoding.UTF8.GetString(buffer); StringReader sr = new StringReader(result); JsonTextReader jsonReader = new JsonTextReader(sr); JsonSerializer serializer = new JsonSerializer(); var r = serializer.Deserialize<TransObj>(jsonReader); txtResult.Text = r.trans_result[0].dst; } } } </span>红色字体须修改成自己的Api key,否则无法运行
这是百度翻译的API文档http://developer.baidu.com/wiki/index.php?title=帮助文档首页/百度翻译/翻译API
Api key获取 须先注册百度开放服务平台,点击开发者服务管理,创建工程,即可形成APikey,如图
至此,大家可以把小程序跑起来了
本文章参考了云菲菲博客http://www.cnblogs.com/yunfeifei/p/4158571.html
左直拳的博客http://blog.csdn.net/leftfist/article/details/38687745