C# – JSON Parsing mit Newtonsoft + Klasse

Folgende JSON Struktur:

{
    "objects":
        {
            "filename":"GU-1000.pdf",
            "mimetype":"application\/pdf",
            "base64Encoded":true,
            "content":"JVBERi0xLjQKJeLjz9MKMyAwIG9iag......."
        }
}

Zunächst muss eine Klasse angelegt werden mittels des Tools: https://app.quicktype.io/

Das Ergebnis:

 public partial class Pdfjson
    {
        [JsonProperty("objects")]
        public Objects Objects { get; set; }
    }

    public partial class Objects
    {
        [JsonProperty("filename")]
        public string Filename { get; set; }

        [JsonProperty("mimetype")]
        public string Mimetype { get; set; }

        [JsonProperty("base64Encoded")]
        public bool Base64Encoded { get; set; }

        [JsonProperty("content")]
        public string Content { get; set; }
    }

    
    public partial class PdfjsonConverter
    {
        public static Pdfjson FromJson(string json) => JsonConvert.DeserializeObject<Pdfjson>(json, Converter.Settings);
    }
    
    

    public static class Serialize
    {
        public static string ToJson(this Pdfjson self) => JsonConvert.SerializeObject(self, Converter.Settings);
    }

    internal static class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
            Converters =
        {
            new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
        },
        };
    }

Anschließend kann mittels Newtonsoft einfach in die Klasse Konvertiert werden:

 Pdfjson PDF = PdfjsonConverter.FromJson(response.Content);

Volsltäniger Code mit Rest Abfrage Restsharp V106

using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

var client = new RestClient("https://my.sevdesk.de/api/v1/CreditNote/624148/getPdf");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "d90537a0fgdfgfd8gabf77a295b4d");
var response = client.Execute(request);

Console.WriteLine(response.Content); // = JSON String

if (response.StatusCode == HttpStatusCode.OK)
{
    Pdfjson PDF = PdfjsonConverter.FromJson(response.Content);
}