0

Of course it's easy to write the code to deserialize from this format. I've already done it, but I don't like.

The single responsibility principle states that I should have a generic class that worries only about this kind of serialization. And the task is generic enough to be coped by a framework.

Revious
  • 7,816
  • 31
  • 98
  • 147

2 Answers2

1

If you converted it to a JSON string like (which should be easy)

var jsonArray = “[{'key':'value'}, {'key':'value'}, {'key':'value'}, {'key':'value'}]”;

then you could easily deserialize it with Json.NET into whatever you want and Json.NET takes care of converting the values to the right types for you:

MyType1[] result = JsonConvert.Deserialize<MyType1[]>(jsonArray);
MyType2[] result = JsonConvert.Deserialize<MyType2[]>(jsonArray);

public class MyType1 
{
    public string key { get; set; }
    public string value { get; set; }
}

public class MyType2
{
    public string key { get; set; }
    public double value { get; set; }
}

or even just as a dictionary (I hope I have the syntax correct, I didn't test it):

var jsonDic = “{{'key':'value'}, {'key':'value'}, {'key':'value'}, {'key':'value'}}”;
var result = JsonConvert.Deserialize<Dictionary<string, string>>(jsonDic);

The single responsibility class (just as an example):

public class KeyValueParser 
{
    public static TResult ParseKeyValueString<TResult>(string keyValueString)
    {
        keyValueString = ConvertToJson(keyValueString);
        TResul result = JsonConvert.DeserializeObject<TResult>(keyValueString);
        return result;
    }

    private static string ConvertToJson(string keyValueString) 
    {
        // convert keyValueString to json
    }   
}

usage

var jsonDic = “{{'key':'value'}, {'key':'value'}, {'key':'value'}, {'key':'value'}}”;
var result = KeyValueParser.ParseKeyValueString<Dictionary<string, string>>(jsonDic);
t3chb0t
  • 16,340
  • 13
  • 78
  • 118
0

I don't really understand the question.

If it is something your program does a lot then move the function to some area that it is easy to get too (or a nuget package if a lot of your systems need it). If it happens in one place in your code put it quite close to that place.

Loofer
  • 6,841
  • 9
  • 61
  • 102