anon
anon

Reputation:

How Do I Configure Json.NET Custom Serialization?

For reasons beyond my control, I have data coming back from an external service being formatted as an array of array of string: [["string_one", "string_two"]]

I am trying to deserialize this into an object with two properties:

public class MyObject
{
    public string PropertyOne { get; set; }
    public string PropertyTwo { get; set; }
}

I'm using Json.NET for all JSON serialization/deserialization. When I attempt to convert the array of array of string, I get an exception saying that JsonArray can't be converted to MyObject. What's the appropriate way to implement this?

Upvotes: 3

Views: 3654

Answers (3)

anon
anon

Reputation:

Ended up implementing this using a JsonConverter. I changed MyObject to look like:

[JsonConverter(typeof(MyObjectConverter))]
public class MyObject
{
    public string PropertyOne { get; set; }
    public string PropertyTwo { get; set; }
}

And then implemented MyObjectConverter:

public class MyObjectConverter : JsonConverter
{
    public override object ReadJson (JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
    {
        int pos = 0;
        string[] objectIdParts = new string[2];

        while (reader.Read())
        {
            if (pos < 1)
            {
                if (reader.TokenType == JsonToken.String)
                {
                    objectIdParts[pos] = reader.Value.ToString();
                    pos++;
                }
            }
            // read until the end of the JsonReader
        }

        return new MyObject(objectIdParts);
    }

    public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException ();
    }

    public override bool CanWrite {
        get {
            return base.CanWrite;
        }
    }

    public override bool CanRead { get { return true; } }
    public override bool CanConvert (Type objectType) 
    {
        return true;
    }
}

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

There is quite a big discrepancy between your target object and the JSON. You could do the mapping manually:

string json = "[[\"string_one\", \"string_two\"]]";
dynamic result = JsonConvert.DeserializeObject(json);
var myObject = new MyObject
{
    PropertyOne = result[0][0],
    PropertyTwo = result[0][1]
};

Upvotes: 2

Richard Szalay
Richard Szalay

Reputation: 84744

Honestly, I'd just deserialize it as string[][] and map that within your domain layer. The amount of time you'll spend messing around with custom serialization is rarely worth it.

Upvotes: 1

Related Questions