I have the following simple class structure:
public class FaactRecordDifferences
{
public string Id { get; set; }
public int Year { get; set; }
public List<FieldDifference> Fields { get; set; }
}
public class FieldDifference
{
public string FieldName { get; set; }
public string FieldValue { get; set; }
public Type type { get; set; }
}
And am trying to turn the resulting json into the following output:
{
"Id": "U123321",
"Year": 2024,
"Fields": {
"SomeFirstField": 1200.21,
"AnotherTestField": "SomeStringValue",
"SomethingHere": 6120.40
}
}
where the IM/FM Field arrays are populated as follows:
-
FieldName from FaactFieldDifference becomes json property name
-
FieldValue from FaactFieldDifference becomes json property value
-
Type used to decide if quotes are necessary in json value or not
To clarify, when type
is typeof(string)
, FieldValue
should be serialized as a string, but otherwise it should be written raw as-is.
How can I accomplish this?
2
Answers
You can define a custom JsonConverter to do so:
I did not understand what otherwise should be written raw it is, because the FieldValue is declared as string. Hence, I assume you would need to store them as the Type defined in the type property.
And use it at the Fields property:
You will have to write a custom
JsonConverterJsonConverter<List<FieldDifference>>
for this:Then apply it to your model as follows:
The converter will serialize
FieldDifference.Value
as a string whenFieldDifference.type
istypeof(string)
, but otherwise it will be written raw as-is as required. Do note that this assumes thatFieldDifference.Value
is well-formed JSON when not serialized as a string.Demo fiddle here.