douxing2652
2019-05-21 12:59
浏览 114

如何从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"));

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题