douxing2652 2019-05-21 12:59
浏览 117
已采纳

如何从HTTPResponseMessage解析PHP Doctrine Querybuilder DateTime到C#DateTime?

I am trying to pass a SQL result from my PHP-made website to my C# APP that I'm making with Xamarin Forms. I've done this by making A REST API endpoint in my PHP application and therefore calling the URL through my C# app. This returns a Json Array with my results. However, I can't find any way to parse the datetime object that I'm receiving to c# datetime as it has ".00000" behind the datetime that i can't get rid of.

SQL

$query = $this->createQueryBuilder('c')
     ->select('partial c.{id, image, title,contentType, createdOn }', 'partial cd.{id, data}', 'partial u.{id, email} ', 'partial ud.{id, screenName, profileImage} ')
            ->join('c.data', 'cd')
            ->join('c.user', 'u')
            ->join('u.data', 'ud')
            ->andWhere('c.user !=:user')
            ->setParameters(
                array(
                    'user' => $this->janVanAllemanId
                )
            )
            ->orderBy('c.modifiedOn', 'DESC')
            ->setFirstResult($offset)
            ->setMaxResults($limit)
            ->getQuery();

    $results = $query->getArrayResult();

JSON Array

        {
    "posts": [
        {
            "id": 3373,
            "contentType": 6,
            "createdOn": {
                "date": "2019-05-21 14:00:14.000000",
                "timezone_type": 3,
                "timezone": "Europe/Amsterdam"
            },
            ...

        },
        {
            "id": 3371,
            "contentType": 6,
            "createdOn": {
                "date": "2019-05-18 14:30:09.000000",
                "timezone_type": 3,
                "timezone": "Europe/Amsterdam"
            },
            ...

        }
    ]
}

As you can see it returns an array with "date", "timezone" and "timezone_type". I can not use this to parse it to a C# DateTime object for the life of me.

This is what I've tried:

PostRepository.cs

 public class PostRepository : Repository
    {
        public async Task<List<Post>> GetNotifications(int userId, int offset = 0, int limit = 16)
        {
            string[] queryParams = { "userId=" + userId, "offset=" + offset, "limit=" + limit };
            string uri =
RestService.GetApiUrl(UrlExtension.POST_NOTIFICATIONS, queryParams);

            List<Post> posts = new List<Post>();
            HttpResponseMessage response = null;
            response = await client.GetAsync(uri);

            if (response.IsSuccessStatusCode)
            {

                PostList postList = await response.Content.ReadAsAsync<PostList>();

                posts = postList.Posts;
            }

            return posts as List<Post>;
        }
}

PostList.cs

public class PostList
    {
        [JsonProperty("posts")]
        public List<Post> Posts { get; set; }
        public PostList()
        {
        }
    }

*Method 1: Through a DateTime property, I tried to deserialize the result.

Post.cs

...
public class Post
{
     [JsonProperty("createdOn")]
     public DateTime CreatedOnDateTime{get;set;}
}

This obviously does not work, because it's not a valid Datetime object. So I tried a JObject and getting the "date" key that you could see above in my Json array:

Post.cs

         ...


public class Post
            {
                 public DateTime CreatedOnDateTime {get;set;}
                 [JsonProperty("createdOn")]
                 public JObject CreatedOn{
                 set{  
                 CreatedOnDateTime= DateTime.ParseExact(value["date"].ToString(),
"M/d/yyyy hh:mm",CultureInfo.CreateSpecificCulture("nl-NL"));

                 }
            }

It succesfully converts to a JObject, but it generates an exception saying that it's not a valid string to convert to a datetime object! I mainly think the reason why this doesn't work is because of the .00000 that magically is appearing behind my dates?!

Anyone knows a way to convert my Json results to a C# DateTime? I really appreciate your help!

  • 写回答

1条回答 默认 最新

  • doudouxuqh198138 2019-05-21 13:10
    关注

    You can use this one:
    CreatedOnDateTime = DateTime.Parse(value["date"].ToString(), CultureInfo.CreateSpecificCulture("nl-NL"));

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器