Sam Carleton
Sam Carleton

Reputation: 1398

System.Text.Json.Deserialize an array into C# class

First off, I am working with the Google recaptcha RESTful service trying to get the JSON object into a class. With WSDL's, Visual Studio will generate all this code for you so that it is easy to work with, but RESTful it seems you have to do everything yourself, am I missing something? I am working with VS2019 and would have thought there is some way to import this stuff to make life easy. I have yet to find anything, so...

Google is returning:

{
  "success": false,
  "error-codes": [
    "invalid-input-response",
    "invalid-input-secret"
  ]
}

I would like to deserialize it into this:

    [DataContract]
    public class GoogleReCaptchaResponse
    {
        [DataMember(Name = "success")]
        public bool Success { get; set; }
        [DataMember(Name = "error-codes")]
        public List<string> ErrorCodes { get; set; }

        [JsonExtensionData]
        public Dictionary<string, object> ExtensionData { get; set; }
    }

I see the error-codes in the ExtensionData, but ErrorCodes is always null. What do I have wrong?

https://dotnetfiddle.net/RtjbwR

Upvotes: 0

Views: 327

Answers (1)

Yehor Androsov
Yehor Androsov

Reputation: 6152

You should use JsonPropertyName attribute from System.Text.Json.Serialization namespace

using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;

public class GoogleReCaptchaResponse
{
    [JsonPropertyName("success")]
    public bool Success { get; set; }

    [JsonPropertyName("error-codes")]
    public List<string> ErrorCodes { get; set; }
}

public class Program
{
    public static void Main()
    {
        GoogleReCaptchaResponse json = System.Text.Json.JsonSerializer.Deserialize<GoogleReCaptchaResponse>("{ \"success\": false, \"error-codes\": [\"invalid-input-response\",\"invalid-input-secret\"]}");
        if (json.ErrorCodes == null)
        {
            Console.WriteLine("no Error Codes");
        }
        else
        {
            Console.WriteLine("Error Codes!");
        }
    }
}

Upvotes: 0

Related Questions