我正在创建一个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 = “\”{\\”FirstName\\”:\\”Steve\\”,\\”LastName\\”:\\”Rogers\\”,\\”DateOfBirth\\”:\\”1920-07-04T00:00:00\\”}\””
result = “{\”FirstName\”:\”Steve\”,\”LastName\”:\”Rogers\”,\”DateOfBirth\”:\”1920-07-04T00:00:00\”}”
result2 = {{
“FirstName”: “Steve”,
“LastName”: “Rogers”,
“DateOfBirth”: “1920-07-04T00:00:00”
}}
我遇到的问题是,在第3次反序列化之前,我无法反序列化为Person对象. result2中的值是我能够成功反序列化为Person的唯一值.有没有更有效的方法来完成这种反序列化?优选地,没有3次迭代.
解决方法
我能够成功运行以下内容(基于
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",4) }; return person; } }