How-to do a Custom ArrayConverter
kirstadt opened this issue · 2 comments
Hi Michaël,
trying some days to get my head around a problem, but I'm pretty much stuck by now.
There are the following json/cbor objects.
{ "value": 0.567 }
{ "value": -110 }
{ "value": "Bar" }
For the first three I found a solution using an extended CborConverterBase<>.
public class DynamicTypeConverter : CborConverterBase<DynamicValue>
{
public override DynamicValue Read(ref CborReader reader)
{
CborDataItemType type = reader.GetCurrentDataItemType();
if (type == CborDataItemType.Unsigned) return new DynamicValue() { value = reader.ReadDouble() };
if (type == CborDataItemType.Signed) return new DynamicValue() { value = reader.ReadDouble() };
if (type == CborDataItemType.Double) return new DynamicValue() { value = reader.ReadDouble() };
if (type == CborDataItemType.String) return new DynamicValue() { valueString = reader.ReadString() };
But I can't get the following one to work.
{ "value":[{"Name":"Beer","Temperature":3,"Count":33},{"Name":"Wine","Temperature":7,"Count":6}]}
I tried adding a new condition and a class holding the three values.
if (type == CborDataItemType.Array)
{
DynamicValue dynamicValue = new DynamicValue();
BarContent context = new BarContent();
int size = reader.ReadSize();
this.ReadBeginArray(size, context);
reader.ReadBeginArray(size, ref context);
while (size > 0 || size < 0 && GetCurrentDataItemType() != CborDataItemType.Break)
{
arrayReader.ReadArrayItem(ref this, ref context);
size--;
}
dynamicValue.BarContent = context;
return dynamicValue;
}
But this doesn't compile. I don't understand the whole context stuff and how to use it properly.
Is this even the right approach doing it in a converter?
Can you please give me some hints how to solve my problem?
Thanks! :-)
Hi,
Can you show some details about the C# model that you use for:
{ "value":[{"Name":"Beer","Temperature":3,"Count":33},{"Name":"Wine","Temperature":7,"Count":6}]}
Having a model like this should just work:
public class MultipleValues
{
public List<DynamicValue> Value { get; set; }
}
That is, you do not need to make a converter for the "list or array" - only for the item type in the array.
a sample is implemented here:
https://github.com/dahomey-technologies/Dahomey.Cbor/blob/master/src/Dahomey.Cbor.Tests/Issues/Issue0097.cs