在控制台应用程序中反序列化Json

时间:2016-06-14 15:27:47

标签: c# json serialization asp.net-web-api deserialization

我正在创建一个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次迭代。

2 个答案:

答案 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)

其他解决方案:

  1. 将Newtonsoft.Json添加到项目中。
  2. enter image description here

    1. 在您的课程中添加使用 - &gt;使用Newtonsoft.Json;
    2. 解析它 - &gt; string json = JsonConvert.SerializeObject(object);