-1

I am trying to fetch data from my server. It is returned as JSON:

item    {{   "name": "Event1",   "tblEventID": "1",   "timeCreated": "2021-08-03 11:47:16",   "timeUpdated": "2021-08-05 15:08:19",   "userID": "6",   "description": "Ein ganz toller Event",   "venueName": "TollesVenue",   "venueAdresse": "VenueStraße in Straßburg",   …}

I tried serializing object like so:

 public static List<EventType> Deserialize(ApiResponse response)
    {
        List<EventType> ad = new List<EventType>();

        var array = (Newtonsoft.Json.Linq.JArray)response.payload;
        foreach (var item in array)
        {
            EventType x = (EventType)(item.ToObject(typeof(EventType)));
            ad.Add(x);

        }
        return ad;
    }

But I am getting the error:

Could not convert string to boolean: 1. Path 'payload[0].displayStartTime'.

So it is failing while trying to convert the string "1" into my eventType where "displayStartTime" is ofc a bool.

Now I can make my type a string and it works fine, but thats not the point. I want to keep it as bool in my model.

However, Since I am basically using one line of code:

EventType x = (EventType)(item.ToObject(typeof(EventType)));

To make the conversion, I cannot access the single steps and intercept the bool / string missmatch.

How could I parse the object, keeping the bool in the model and deserializing the whole json?

E_net4
  • 27,810
  • 13
  • 101
  • 139
innom
  • 770
  • 4
  • 19

1 Answers1

0

I managed to solve this by using a custom converter like desribed here:

How do I get Newtonsoft to serialize a bool as false, not False or "false"

Basically I overwrote the JasonReader:

 public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer )
    {
        switch (reader.Value.ToString().ToLower().Trim())
        {
            case "true":
            case "yes":
            case "y":
            case "1":
                return true;
            case "false":
            case "no":
            case "n":
            case "0":
                return false;
        }
innom
  • 770
  • 4
  • 19
  • Why was it trying to map a field named `DisplayStartTime` as a boolean in the first place? – Joel Coehoorn Aug 05 '21 at 15:57
  • Because of my model i define displayStartTime as a bool. :) – innom Aug 05 '21 at 16:01
  • I get it now... it's "yes, display the start time", or "no, don't display the start time". It looked at first to me like a field for the timestamp when display started. – Joel Coehoorn Aug 05 '21 at 16:05
  • right it is a yes or no question: "Display the starting time?" And not a request: "Display the starting time". ;) – innom Aug 05 '21 at 16:06
  • FYI - https://stackoverflow.com/questions/234591/upper-vs-lower-case and maybe trim before calling tolower/toupper – Rand Random Aug 06 '21 at 08:56