我有以下应用程序用于发出以JSON格式返回数据的GET请求:
class Program
{
static void Main(string[] args)
{
RunAsync().Wait();
}
static async Task RunAsync()
{
using (var client = new HttpClient())
{
//Send HTTP request
client.BaseAddress = new Uri("httpMyURI");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("api/people/.....");
if (response.IsSuccessStatusCode)
{
var person = response.Content.ReadAsAsync<IEnumerable<Persons>>().Result;
foreach (var i in person)
{
Console.WriteLine("{0}\t{1}-{2}", i.FirstName, i.LastName, i.Peopleid);
}
}
}
}
}
class Persons
{
public string Peopleid { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
如何根据我得到的结果创建xml文件?我想我首先必须将JSON转换为xml然后创建一个XML文件?
答案 0 :(得分:1)
您可以使用Newtonsoft Json.NET库轻松完成此操作。 请参阅操作中的示例:http://www.newtonsoft.com/json/help/html/convertingjsonandxml.htm
你所追求的是
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
答案 1 :(得分:0)
保存xml文档非常简单
string responseAsString = response.Content.ReadAsStringAsync().Result; //Read response
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(responseAsString); //Convert to XML
doc.Save("myfilename.xml"); //Save XML to file