简体   繁体   中英

Migrating from NewtonSoft.Json to System.Text.json

We have an POST endpoint which accepts dictionary as request body.

        public class A {
public IDictionary<string, JsonElement?>? Values { get; set; };
    }

Earlier we were accepting JToken. We have replaced JToken with JsonElement during migration.

The request body is as below

{"tags": {
    "Some-tag": "Tags-value"
  }
}

It was working seamlessly when it was JToken. After migration, I am getting error "Error converting value "Tags-value" to type 'System.Nullable`1[System.Text.Json.JsonElement]"

Any help will be appreciated.

This is configurable when deserializing or serializing. Maybe you need other options too.

     public static readonly JsonSerializerOptions SettingsOptions = new()
            {
                NumberHandling = JsonNumberHandling.AllowReadingFromString,
                UnknownTypeHandling = JsonUnknownTypeHandling.JsonElement
            };

Then you can use this option like this:

 Data example = JsonSerializer.Deserialize<Data>(content, JsonSerializerConfig.SettingsOptions);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM