0

I have UWP app where I get my json , write list and Binf to View

Here is code of View Model:

 public class TopPostsViewModel : INotifyPropertyChanged
{
    private List<Child> postsList;

    public List<Child> PostsList
    {
        get { return postsList; }
        set { postsList = value; OnPropertyChanged(); }
    }

    public TopPostsViewModel()
    {
        Posts_download();
    }


    public async void Posts_download()
    {
        string url = "https://www.reddit.com/top/.json?count=50";

        var json = await FetchAsync(url);


        RootObject rootObjectData = JsonConvert.DeserializeObject<RootObject>(json);
        PostsList = new List<Child>(rootObjectData.data.children);

    }
    private async Task<string> FetchAsync(string url)
    {
        string jsonString;

        using (var httpClient = new System.Net.Http.HttpClient())
        {
            var stream = await httpClient.GetStreamAsync(url);
            StreamReader reader = new StreamReader(stream);
            jsonString = reader.ReadToEnd();
        }

        return jsonString;
    }

In json I have data.created_utc field. For example it's like this created_utc: 1446179731. I read that this is unix timestamp

Here is my classes: Classes

I need to convert it to normal date. How I can do this and write to List back?

So my question is more about, how to take field and write it back.

Logan
  • 121
  • 13
  • 3
    Possible duplicate of [how convert unix timestamp to datetime](https://stackoverflow.com/questions/28305153/how-convert-unix-timestamp-to-datetime) – Jeric Cruz Jun 20 '17 at 03:54
  • Nope, edit my question@JericCruz – Logan Jun 20 '17 at 03:57
  • @Logan What do you mean by "write it back"? – Vijay Nirmal Jun 20 '17 at 07:55
  • Take data, convert it to normal date and write it back to List, or, how I can convert it?@VijayNirmal – Logan Jun 20 '17 at 07:57
  • @Logan I don't understand your problem. 1. It is very easy to Take data 'data2.created_utc', 2. You can convert using [this](https://stackoverflow.com/questions/28305153/how-convert-unix-timestamp-to-datetime) post, 3. What is the problem in writing the result in `List`? (OR) am I missing something? – Vijay Nirmal Jun 20 '17 at 08:17
  • How to convert I know, but how to update the List?@VijayNirmal – Logan Jun 20 '17 at 08:21
  • @Logan You want to update the Value in List. Am I right? If yes then you can't directly update the value in List because raw `created_utc` is in double but converted value will be in `DateTime` so add a Property in Child class with `DateTime` datatype and assign the new value to it. – Vijay Nirmal Jun 20 '17 at 08:39

2 Answers2

3

You will have to add another property in Data2 class to get the converted data in DateTime.

    [JsonIgnore]
    public DateTime created_utc
    {
        get
        {
            var unix = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            return unix.AddSeconds(this.created_utcUnix);
        }
        set
        {
            var unix = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            this.created_utcUnix = Convert.ToInt64((value - unix).TotalSeconds);
        }
    }

    [JsonProperty("created_utc")]
    public double created_utcUnix { get; set; }

Now you can always use created_utcCustom in your client code

New Code : https://pastebin.com/A4GReYHj

saurabh
  • 724
  • 3
  • 17
2

While @saurabh have a good way. But I think you may want to convert it and dont change the class.

You can use JsonConverter to convert it.

public class Data2
{
   [JsonConverter(typeof(UnixConvert))]
   public DateTime created_utc{set;get;}
}

I have a foo class. The foo class have a property which name is created_utc.

    class Foo
    {
        [JsonConverter(typeof(UnixConvert))]
        public DateTime created_utc { set; get; }
    }

UnixConvert is a JsonConverter

    class UnixConvert : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var time = ToUnixTimestamp((DateTime) value);
            writer.WriteValue(time);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            long unixTimeStamp = long.Parse(reader.Value.ToString());
            return UnixTimeStampToDateTime(unixTimeStamp);
        }

        public override bool CanConvert(Type objectType)
        {
            return true;
        }

        private static DateTime UnixTimeStampToDateTime(long unixTimeStamp)
        {
            System.DateTime dtDateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
            dtDateTime = dtDateTime.AddSeconds(unixTimeStamp);
            return dtDateTime;
        }

        public static long ToUnixTimestamp(DateTime time)
        {
            var date = new DateTime(1970, 1, 1, 0, 0, 0, time.Kind);
            var unixTimestamp = System.Convert.ToInt64((time - date).TotalSeconds);

            return unixTimestamp;
        }
    }

I write a test code:

        Foo foo = new Foo()
        {
            created_utc = DateTime.Now
        };
        var str = JsonConvert.SerializeObject(foo);
        foo = JsonConvert.DeserializeObject<Foo>(str);

I can see it can run.

See https://stackoverflow.com/a/28305303/6116637

lindexi
  • 4,182
  • 3
  • 19
  • 65