1,285 questions
1
vote
3
answers
76
views
ASP.NET Core single-file application with default serialization causing error
I'm trying to migrate a simple app with a basic API to crunch numbers to generate a load, to a single-file application as a proof of concept.
generate-load-server.cs:
#! /usr/bin/env dotnet run
#:sdk ...
1
vote
2
answers
154
views
.NET ReadFromJsonAsync<List<T>>() throws JsonException when API response contains wrapper object
I am developing a layered .NET project with API, BLL, DAL, and UI layers.
The UI layer calls the API using a generic API repository built with HttpClient.
My project structure is roughly like this:
...
1
vote
1
answer
101
views
How to release a file written with JsonSerializer.Serialize(Utf8JsonWriter)?
I'm testing a method that reads a JSON file. So in the setup, I first create said JSON file, like this:
string pathOfRelevantStuff = "path";
string fileOfRelevantStuff = Path.Combine(...
0
votes
0
answers
67
views
How to get JsonSerializer.Deserialize<> to not leave objects as JsonElement? [duplicate]
When I run System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>> all values are converted to JsonElement, instead of the actual value. I expect numbers to be converted to ...
1
vote
1
answer
196
views
Can System.Text.Json tolerate an unrecognized type discriminator during deserialization?
I would like to be tolerant if the JSON payload contains a type my app doesn't know about. Ideally I would like to get information about the errors along with the deserialized object, but at a minimum ...
2
votes
1
answer
129
views
Add JsonObject to JsonArray with AOT
I have the following C# code in a .NET 9 project that will be AOT-compiled:
var deviceEntries = new JsonArray();
foreach (string deviceId in deviceIds)
{
var deviceEntry = new JsonObject
{
...
1
vote
1
answer
277
views
Using "System.Text.Json.JsonSerializer" to generate OpenAPI source code
I am binding an OpenAPI 3.0 JSON file in my C# project with .NET Framework 4.8.
While doing this, I want to adjust the .json configuration to make the code generated using OpenAPI code generator use ...
1
vote
1
answer
121
views
How to create a custom json Deserializer that returns the fields name and the values from a dynamic json [duplicate]
I want to create a JSON deserializer that returns a specific type.
The JSON can be either in a format that marches SpecificOne or SpecificTwo. We only know that at runtime. Once we deserialize it, I ...
Advice
0
votes
2
replies
298
views
System.Text.Json Polymorphic Deserialization not binding Type Discriminator property
I'm trying to do a polymorphic deserialization using System.Text.Json in net-8.0. Here is my schema.
[JsonPolymorphic(TypeDiscriminatorPropertyName = "type")]
[JsonDerivedType(typeof(Manager)...
1
vote
2
answers
160
views
Can I deserialize a nested JSON property in place of its object
I want to serialize a nested JSON structure using System.Text.Json into regular C# classes, but I have a specific case where I want a single property of a nested object instead of the full object ...
-2
votes
3
answers
385
views
How to fix "Could not load file or assembly 'System.Threading.Tasks.Extensions`" exception when using System.Text.Json in .NET Framework?
I am trying to deserialize a JSON string in C#:
JsonObject json = JsonSerializer.Deserialize<JsonObject>
("{\"columnsperrow\":\"1\",\"columnwidths\":[400.0]...
2
votes
2
answers
175
views
How to use the [DefaultValue] attribute to ignore boolean = true properties in JSON serialization
This is a follow up question to the Ignore boolean property = true in JSON serialization.
I have a record with multiple bool properties, some of them having default value true and some false:
private ...
2
votes
1
answer
94
views
Ignore boolean property = true in JSON serialization
I have a record with a bool property that has default value = true:
private record MyRecord()
{
public bool BoolProperty { get; init; } = true;
}
I want to ignore the "BoolProperty":...
1
vote
2
answers
203
views
How to suppress writing empty string value to JSON (C#, .NET 8, System.Text.Json)
I have a property in an object; if its value is string.Empty, I don't want this property in the serialized JSON. I have seen this solution:
public class JsonEmptyString : JsonConverter<string>
{
...
0
votes
2
answers
131
views
Is it possible to use generic argument of a type for its attribute parameter (JsonConverter)?
Use case: I want to write a JsonConverter for a generic type like this, but I cannot apply it to the type itself:
public class EditingModelConverter<T> : JsonConverter<EditingModel<T>&...
2
votes
1
answer
94
views
Custom attribute that copies the JsonIgnore attribute's functionality
I want to create a custom attribute that basically does the same as [JsonIgnore] from System.Text.Json, but has a different name.
The reason for that is that we have virtual properties, that among ...
6
votes
1
answer
313
views
System.Text.Json is not handling Quaternions - is there some Json settings we need to set/support?
We are having some issues deserialising classes with Quaternion properties.
We are seeing very odd behaviour.
The Quaternions deserialise correctly (we can do a custom JsonConverter to confirm the ...
2
votes
1
answer
156
views
Deserializing Interface Types in C# projected on records
I'm deserializing interfaces mapped to usual classes with a custom IJsonTypeInfoResolver. The resolver looks similar to this:
public class InterfaceMappingResolver : IJsonTypeInfoResolver
{
...
1
vote
0
answers
69
views
System.Text.Json deserialization not deserializing the Json string [duplicate]
We have a class as shown below:
public class KeyVal<Key, Val>
{
public Key Id { get; set; }
public Val Text { get; set; }
public KeyVal() { }
public KeyVal(Key key, Val ...
1
vote
0
answers
64
views
System.Text.Json.Serialization.JsonConverter<T> which globally omits properties with a given attribute on writing? [duplicate]
Imagine that you have marked all sensitive data with the [Secret] attribute throughout your project and want it all to be deleted when you save your models to disk, i.e. the following program
using ...
1
vote
1
answer
135
views
Polymorphic deserialize JSON using DI container to create instances
Consider these model classes:
[JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")]
[JsonDerivedType(typeof(A), typeDiscriminator: nameof(A))]
[JsonDerivedType(typeof(B), ...
1
vote
0
answers
315
views
System.Text.Json source generation calling GetTypeInfo excessively, slower than Newtonsoft.Json in Unity 6
I'm migrating from Newtonsoft.Json to System.Text.Json in my Unity project due to its reported benefits: lighter memory footprint and better performance through source generation, which should ...
1
vote
1
answer
490
views
Adding modifiers to System.Text.Json serialization when using source generation
I'm currently using the following code to set up a System.Text.Json JsonSerializerOptions object that alphabetizes properties upon serialization:
public static readonly JsonSerializerOptions ...
7
votes
2
answers
1k
views
Convince System.Text.Json to ignore a property with the `required` modifier
I've got a simple type:
public class Example {
[JsonIgnore]
public required string RequiredButDontSerialize {get;init;}
public string AnotherPropertyWhatever {get;init;}
}
that causes System....
0
votes
0
answers
80
views
How to globally reject null for non-nullable reference types in ASP.NET Core 9 Web API with System.Text.Json?
Background
I have an ASP.NET Core 9 Web API project with [nullable reference types] enabled (<Nullable>enable</Nullable>). In my request DTOs, I declare certain properties as non‑nullable, ...
0
votes
1
answer
129
views
System.ArrayTypeMismatchException when using System.Text.Json with .NET Framework 4.7 in MSTest
I'm currently using .NET Framework 4.7 along with MSTest (all packages are up to date). I'm trying to deserialize a JSON string using System.Text.Json as shown here:
using System.Text.Json;
private ...
0
votes
0
answers
75
views
ASP.NET Web API - Model binder validation property name
I have a basic ASP.NET Web API project. When I send a request, the serialization is done using System.Text.Json. However, when I send a non-valid json, for example text instead of number, it returns a ...
2
votes
2
answers
146
views
JsonSerializer not working in release build uwp
When serializing a complex record in an UWP application, it works fine in debug mode, but in release mode, when application is packaged using Windows application packaging project, the JsonSerializer ...
2
votes
0
answers
51
views
How do you limit indentation depth when serializing with System.Text.Json?
I am duplicating this question, except applying it to System.Text.Json: How do you limit indentation depth when serializing with Newtonsoft.Json.
When serializing an object using System.Text.Json, is ...
1
vote
1
answer
66
views
How to Deserialize json document using reflection.emit.modulebuilder in system.text.json [closed]
We have a local Web API used for internal clients to retrieve data. We use application/json to transport the data across the Web API.
The retrieved JSON data has a simple structured class 'Response'. ...
0
votes
1
answer
173
views
System.Text.Json.JsonSerializer.Deserialize is not deserializing object correctly [duplicate]
I am trying to use System.Text.Json library for performance improvement. When I am trying to convert it, System.Text.Json is not able to deserialize the object but Newtonsoft.Json able to do so.
How ...
1
vote
1
answer
138
views
System.Text.Json doesn't deserialize IEnumerable with a private getter
I'm deserializing a series of objects from a third party source. There are a number of different formats, but once I have deserialized them, I want them all to have a common interface. So I have my ...
-5
votes
1
answer
173
views
How to enumerate a JsonElement array backwards?
I have a System.Text.JsonElement with about 100 elements inside. I know of EnumerateArray(), but is there a way to do this backwards, meaning: Start at the last element of the list and enumerate until ...
5
votes
2
answers
448
views
How can I remove a property from JsonElement?
I have my JSON serialised into a single line.
How can I load it, remove a property, and then serialise it to a single line again?
internal class Program
{
static void Main(string[] args)
{
...
1
vote
1
answer
203
views
The converter handles Int32 but is being asked to convert Nullable<Int32>
I'm implementing a custom JsonConverter that handles nullable types. Specifically, it turns empty strings and empty arrays into null.
I've managed to piece together this: (with help from here)
public ...
1
vote
2
answers
309
views
Serialise base class properties first in System.Text.Json
Given a sample class structure like this
public class ParentClass {
public int ParentProperty1 { get; set; }
public int ParentProperty2 { get; set; }
}
public class ChildClass: ParentClass {
...
2
votes
3
answers
219
views
Why does an inherited class not get JSON serialized correctly?
I want to create a JsonSerializable class, that I can inherit from. See this code:
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
public interface IJson
{
string ...
2
votes
1
answer
315
views
Could not load file or assembly 'System.Text.Json' in Production (works locally) while using .NET 8
In my production environment while running a console application wrapped using an installer I get this error:
System.IO.FileNotFoundException: Could not load file or assembly 'System.Text.Json, ...
0
votes
1
answer
229
views
The type or namespace name 'JsonSerializer' could not be found
I'm trying to use JsonSerializer in a simple .NET 8.0 console application, but I'm getting the error:
The type or namespace name 'JsonSerializer' could not be found (are you missing a using directive ...
0
votes
1
answer
95
views
How to get JsonPropertyName string and concatenate with others in dot.notation? (C# and Salesforce related)
I have built a C# library to make queries on Salesforce using Web Calls.
This is an example of implementation:
var myQuery = new SalesForceQueryBuilder<MyCoustomUnicornEntity>()
...
0
votes
0
answers
34
views
JObject data is lost or serialized incorrectly when sending request in .NET 8 [duplicate]
I'm upgrading .NET to version 8 and a “problem” is occurring that wasn't happening before.
I have a class A that has a field of type JObject from the Newtonsoft.Json library and this field uses the ...
0
votes
1
answer
77
views
How to make Deserialization work with a private field?
I'm wanting to only expose a list as ReadOnly but it's, but while trying to accomodate that for Deserialization, it's not currently working.
Firstly, to confirm Serialization:
{
"StartTime"...
5
votes
1
answer
252
views
Why can't I deserialize JSON to an object with a List<T> property
With .NET 8, using System.Text.Json, I can serialize/deserialize a List<T>. I can also serialize an object with a property of type List<T>. However, I cannot deserialize that object. Here ...
1
vote
1
answer
119
views
Deserializing JSON text to an object in C#
I have the following class:
public class DeviceInfo
{
public string? ip { get; set; }
public string? deviceKey { get; set; }
public long time { get; set; }
public string? version { get;...
2
votes
3
answers
348
views
How to convert Newton Json ReferenceLoopHandling to System.Text.Json
I'm trying to convert this line:
builder.Services
.AddControllers()
.AddNewtonsoftJson(o => o.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
...
1
vote
1
answer
2k
views
I can't bypass the System.ArgumentException: '.NET number values such as positive and negative infinity cannot be written as valid JSON."
I am getting the following exception when I am trying to serialize a double that has the value NaN, via JsonConverter
The exception is:
System.ArgumentException: '.NET number values such as positive ...
1
vote
0
answers
103
views
how to make STJ use exiting property for polymorphic de/serialization
I setup my poly serialization with one abstract class and couple concrete classes. However the property which I want to use as a discriminator is already present in a base class as a string. Now when ...
4
votes
2
answers
768
views
With System.Text.Json, is there a way to EXCLUDE properties from a BASE class from serialization?
For example, I have a class that derives from ObservableValidator and my resulting serialization then includes HasErrors. I want to only include my derived class's properties and don't have access to ...
0
votes
0
answers
98
views
ASP.NET Core Web API : [FromBody] validation doesn't work for [Required] properties
I have the following ASP.NET Core Web API endpoint. This endpoint is auto-generated through a workflow that uses a TypeSpec definition, which is then converted to OpenAPI and then to an ASP.NET Core ...
1
vote
1
answer
396
views
Exception about missing TypeInfoResolver while using BenchmarkDotNet to perform a JSON source generator serialization
I am getting an exception:
> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
---> System.InvalidOperationException: TypeInfoResolver '...