我正在创建一个Web API端点,它将充当检索我们的应用程序配置,执行日志记录等的服务。我遇到的问题是能够在控制台应用程序中反序列化Json。
设置
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
}
Web API
[HttpGet]
[Route("Person")]
public IHttpActionResult GetPerson()
{
Person person = new Person
{
FirstName = "Steve",
LastName = "Rogers",
DateOfBirth = new DateTime(1920, 7, 4)
};
return Ok(JsonConvert.SerializeObject(person));
}
控制台应用
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost");
var response = client.GetAsync("api/Person").Result;
var data = response.Content.ReadAsStringAsync().Result;
var person = DeserializeJson<Person>(data);
}
public static T DeserializeJson<T>(string input)
{
var result = JsonConvert.DeserializeObject(input);
var result2 = JsonConvert.DeserializeObject(result.ToString());
return JsonConvert.DeserializeObject<T>(result2.ToString());
}
值
data =&#34; \&#34; {\\&#34; FirstName \\&#34;:\\&#34; Steve \\&#34;,\\&#34; LastName \\&#34;:\\&#34;罗杰斯\\&#34;,\\&#34; DATEOFBIRTH \\&#34;:\\&#34; 1920-07-04T00:00:00 \\&#34;} \&#34;&#34;
result =&#34; {\&#34; FirstName \&#34;:\&#34; Steve \&#34;,\&#34; LastName \&#34;:\&#34 ;罗杰斯\&#34; \&#34; DATEOFBIRTH \&#34;:\&#34; 1920-07-04T00:00:00 \&#34;}&#34;
result2 = {{ &#34; FirstName&#34;:&#34; Steve&#34;, &#34;姓氏&#34;:&#34;罗杰斯&#34;, &#34; DateOfBirth&#34;:&#34; 1920-07-04T00:00:00&#34; }}
我遇到的问题是,在第3次反序列化之前,我无法反序列化Person
对象。 result2
中的值是我唯一能够成功反序列化为Person
的值。有没有更有效的方法来完成这种反序列化?优选地,没有3次迭代。
答案 0 :(得分:4)
我能够成功运行以下内容(基于this Microsoft article):
控制台应用
static void Main(string[] args)
{
RunAsync().Wait();
}
static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:3963/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("api/Person");
Person product = await response.Content.ReadAsAsync<Person>();
}
}
<强>控制器:强>
public class PersonController : ApiController
{
public Person GetPerson()
{
Person person = new Person
{
FirstName = "Steve",
LastName = "Rogers",
DateOfBirth = new DateTime(1920, 7, 4)
};
return person;
}
}
答案 1 :(得分:0)
其他解决方案: