2

I have two classes that look like this:

public class Field
{
    public string Name { get; set; }
    public FieldType FieldType { get; set; }
}

public class FieldType
{
    public Dictionary<string, object> Settings { get; set; }

    public static readonly FieldType Text = new FieldType()
    {
        Settings = new Dictionary<string, object>() { { "setting 1", "" }, { "setting 2", "" } }
    };
}

And I'd like to deserialize the following json:

{
    "name": "First Name",
    "fieldType": "Text"
}

So that the FieldType property is correctly assigned the static FieldType of 'Text'.

Do I need to modify my FieldType class? Or do I need some custom JsonSerializerSettings?

Currently I'm getting the error: Error converting value "Text" to type 'FieldType'. Path 'fieldType

EdB
  • 63
  • 1
  • 5

2 Answers2

0

The way your json looks, involves that fieldType to be an instance of a string type, so if you change the class against which you want to deserialize to somethig like:

public class Field
{
    public string Name { get; set; }
    public string FieldType { get; set; }
}

The deserialize will work.

Do I need to modify my FieldType class?

No, you don't need to modify your FieldType class, you can keep it as it is, deserialize into a Field and then with the values from the field class you can populate your FieldType class or do anything you want.

You can not deserialize into a static property as you can see this question for more details. If you need to store the data in a static field, and to receive it into a static field, then you should not try to use serialization.

Community
  • 1
  • 1
meJustAndrew
  • 6,011
  • 8
  • 50
  • 76
  • The FieldType can only be one of a fixed number of values. Is there a better way of converting the string `text` to a FieldType member without having this dummy property in the Field class? – EdB Jul 12 '16 at 17:10
  • @EdB I have updated my answer, I hope it's clear now. – meJustAndrew Jul 12 '16 at 17:17
0

You can use the ReadObject method of the DataContactJsonSerializer

DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Field));
MemoryStream stream1 = new MemoryStream();
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);

Field field = (Field)ser.ReadObject(stream1);
SamN
  • 7
  • 1
  • 3