0

From an HTTP GET Request I have the following result as string:

{
  "id": "5963363",
  "private": "0",
  "created_at": "2021-06-02 16:15:40",
  "release_date": "2021-06-02 16:15:40",
  "release_timestamp": 1622643340,
  "user_id": "10037997",
  "duration": "16",
  "permalink": "the-shortest-interview-of-magnus-carlsen-only-10-seconds",
  "description": "",
  "geo": "",
  "tags": "",
  "taged_artists": "",
  "bpm": "92.5",
  "key": "Bm",
  "license": "",
  "version": "",
  "type": "",
  "downloadable": "1",
  "genre": "Other",
  "genre_slush": "other",
  "title": "The Shortest Interview of Magnus Carlsen - ONLY 10 SECONDS!",
  "uri": "https://api-v2.hearthis.at/sergiu-molnar/the-shortest-interview-of-magnus-carlsen-only-10-seconds/",
  "permalink_url": "https://hearthis.at/sergiu-molnar/the-shortest-interview-of-magnus-carlsen-only-10-seconds/",
  "thumb": "https://images.hearthis.at/1/_/2/_/uploads/dummy/w200_h200_q70_----1_2021_04-2.jpg",
  "artwork_url": "https://images.hearthis.at/1/_/2/_/uploads/dummy/w500_q70_----1_2021_04-2.jpg",
  "artwork_url_retina": "https://images.hearthis.at/1/_/2/_/uploads/dummy/w1000_q70_----1_2021_04-2.jpg",
  "background_url": "https://images.hearthis.at/1/_/2/_/uploads/dummy/w565_h565_c000000_q70_----1_2021_04-2.jpg",
  "waveform_data": "https://cdn.hearthis.at/_/wave_data/10037997/3000_6ab732ed56cc403f09c0dc9f86f80342.mp3_1622643340.js",
  "waveform_url": "https://cdn.hearthis.at/_/cache/waveform_mask/5/9/5963363.png",
  "user": {
    "id": "10037997",
    "permalink": "sergiu-molnar",
    "username": "Sergiu Molnar",
    "caption": "",
    "uri": "https://api-v2.hearthis.at/sergiu-molnar/",
    "permalink_url": "https://hearthis.at/sergiu-molnar/",
    "avatar_url": "https://images.hearthis.at/1/_/2/_/uploads/dummy/w512_q70_----1_2021_08-2.jpg"
  },
  "stream_url": "https://hearthis.app/sergiu-molnar/the-shortest-interview-of-magnus-carlsen-only-10-seconds/listen/?s=vCc",
  "preview_url": "https://preview.hearthis.at/files/6ab732ed56cc403f09c0dc9f86f80342.mp3",
  "download_url": "https://hearthis.app/sergiu-molnar/the-shortest-interview-of-magnus-carlsen-only-10-seconds/download/",
  "download_filename": "The Shortest Interview of Magnus Carlsen - ONLY 10 SECONDS! (hearthis.at).mp3",
  "playback_count": "1",
  "download_count": "0",
  "favoritings_count": "0",
  "reshares_count": "0",
  "comment_count": "0",
  "played": false,
  "favorited": false,
  "liked": false,
  "reshared": false
}

As you can see, almost all properties are strings even these should be int or date.

What I'm trying to do is to Deserialize the object and Convert the properties. For this, I'm using Newtonsoft.Json as follow:

JsonConvert.DeserializeObject<TrackDetails>(response);

This is the TrackDetails class:

public class TrackDetails
{
     [JsonProperty("id")]
     public string Id { get; set; }

     ...
}

Because in the result, the Id is a string and I want this as int, after I read those articles:

I have tried to create a custom converter like this one:

public class StringToIntConverter : JsonConverter
{
     public override bool CanConvert(Type objectType)
     {
          return (objectType == typeof(string));
     }

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

     public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
     {
          writer.WriteValue(int.Parse((string)value));
     }
}

And this was applied like this:

[JsonProperty("id")]
[JsonConverter(typeof(StringToIntConverter))]
public string Id { get; set; }

But I'm getting the following errors:

Newtonsoft.Json.JsonSerializationException
  Message=Error setting value to 'Id' on 'API.Models.TrackDetails'.

Inner Exception 1:
  InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'.
Sergiu Molnar
  • 865
  • 1
  • 11
  • 22
  • 2
    Shouldn't `public string Id { get; set; }` be `public int Id { get; set; }` ? As for dates, [the standard way](https://datatracker.ietf.org/doc/html/draft-ietf-json-i-json#section-4.3) is to serialize them as ISO8601 strings. Have you tried using `DatetTime` as the type for `release_timestamp` ? – Panagiotis Kanavos Jun 03 '21 at 09:13
  • Yes, I also tried to declare them as `int` or `DateTime` (the type I expected) assuming they will be automatically converted, but like this, I'm getting the following error for `int` for e.g: `Could not convert string to boolean: 0` – Sergiu Molnar Jun 03 '21 at 09:15
  • 1
    That's a different thing completely. `0` is a number, not a bool (true,false). There's no if or but about dates. That's how they work. [ints are also converted automatically](https://stackoverflow.com/questions/41783225/json-deserialization-string-is-automatically-converted-to-int). – Panagiotis Kanavos Jun 03 '21 at 09:16
  • With converter, should you not specify the the required type `[JsonConverter(typeof(StringToIntConverter))] public int Id {get ;set;}`? In your case, it should be `int Id` instead of `string Id` – user1672994 Jun 03 '21 at 09:18
  • 1
    As for booleans, what you posted uses `"played": false,`, not a string and definitely not a number. There's `"downloadable": "1"` but I suspect that's really a number, as the rest of the document uses boolean values – Panagiotis Kanavos Jun 03 '21 at 09:18
  • Post the *actual* class you tried to use, not just a single property. I suspect most if not problems are caused by typos and mismatches. – Panagiotis Kanavos Jun 03 '21 at 09:20
  • Oh, I understood the problem. So I have to create a converter only from `string` to `bool`. I understood. Thank you, guys. – Sergiu Molnar Jun 03 '21 at 09:22
  • 1
    @SergiuMolnar only if you want to handle eg `private` as a boolean, even though the document clearly uses boolean values for `played`, `favorited` etc. Are you *sure* that `private` is a boolean? Shouldn't you contact the author then? Clearly, they're using different ways to output the same type. Unless those properties *aren't* booleans but numbers? – Panagiotis Kanavos Jun 03 '21 at 09:23
  • Yup, that was the problem. In the response, as you mentioned @PanagiotisKanavos `"downloadable": "1"` could not be converted from string to bool without an explicit converter. – Sergiu Molnar Jun 03 '21 at 09:25

0 Answers0