Home > Back-end >  Have a JsonConverter that is only used during deserialization
Have a JsonConverter that is only used during deserialization

Time:03-30

My goal is to deserialize this JSON into a Dictionary<string, TValue>.

[
  {
    "key": "foo",
    "value": 42
  }
]

My approach is a custom JsonConverter<Dictionary<string, TValue>> with an appropriate JsonConverterFactory.

Deserialization is working fine, but I'm struggling with the serialization part. During serialization, I want this to be serialized like any other dictionary, so the result from serializing the same value as above should be

{
  "foo": 42
}

My idea was to just pass it down to the default JsonDictionaryConverter<TDictionary, TKey, TValue>. This is my Write method:

public override void Write(Utf8JsonWriter writer, Dictionary<string, TValue> value, JsonSerializerOptions options)
{
    var newOptions = new JsonSerializerOptions(options);
    newOptions.Converters.Remove(this);
    JsonSerializer.Serialize(writer, value, newOptions);
}

However I always get a NullReferenceException in JsonDictionaryConverter<TDictionary, TKey, TValue>OnTryWrite(Utf8JsonWriter writer, TDictionary dictionary, JsonSerializerOptions options, ref WriteStack state). The Exception happens here (Line 299), because state.Current.JsonTypeInfo.ElementTypeInfo is null.

state.Current.DeclaredJsonPropertyInfo = state.Current.JsonTypeInfo.ElementTypeInfo!.PropertyInfoForTypeInfo;

Does anyone have an idea how I can just skip my converter during serialization or have this Exception go away?

CodePudding user response:

I suggest using helper class and ToDictionary.

var json = @"[
    {
      ""key"": ""foo"",
      ""value"": 42
    }
  ]";

var o = JsonSerializer.Deserialize<List<Z>>(json, new JsonSerializerOptions { IncludeFields = true});
var d = o!.ToDictionary( x => x.key, x => x.value);

Console.WriteLine(JsonSerializer.Serialize(d, new JsonSerializerOptions {WriteIndented = true, IncludeFields = true}));

class Z { public string? key {get;set; } public int? value {get; set;} }

This prints

{
  "foo": 42
}

CodePudding user response:

You May Refer I Use JSON convert for convert datatable to JSON format

public static DataTable JsonToDataTable(string Json)
        {
            DataTable dt = new DataTable();
            try
            {
                dt = (DataTable)JsonConvert.DeserializeObject(Json, (typeof(DataTable)));
            }
            catch (Exception ex)
            {
                string chk = ex.Message;
                dt = new DataTable();
            }
            return dt;
        }
  • Related