0

I'm using Json.Net and I want to deserialize a json List which look like this :

[
{ "name":"blabla", "price":"50" },
{ "name":"blabla", "price":"50" },
...
]

So I've done

List<PriceItem> list = JsonConvert.DeserializeObject<List<PriceItem>>(json, new DictionnaryJsonConverter());

But I want to deserialize only items with certain names in this line, basicly have a function isNameValid(string name) which if return true put the item in the list and if false get rid of it.

I could do the computation in a second read but I need to have good perf on this function.

I've tried to do a custom JsonConverter like this but I don't know how to write the List ReadJson function

public class CustomJsonConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        if (objectType == typeof(PriceItem))
        {
            return true;
        }
        else if (objectType == typeof(List<PriceItem>))
        {
            return true;
        }
        throw new NotImplementedException();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        Object obj = new Object();

        if (objectType == typeof(PriceItem) )
        {
            obj = new PriceItem();
            ((PriceItem)obj).Name = reader.ReadAsString();
            ((PriceItem)obj).Price = reader.ReadAsString();
        }
        else if (objectType == typeof(List<PriceItem>))
        {
            // ?????
        }

        return obj;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
dekajoo
  • 2,024
  • 1
  • 25
  • 36

1 Answers1

1

To be honest, I'm not sure you really gain much by using a JsonConverter here to do the filtering. Unless your JSON is absolutely huge and you're worried about memory consumption, the simplest way to get what you need is to deserialize the list normally and then filter it after the fact. You can do it with just a single line of code:

List<PriceItem> list = JsonConvert.DeserializeObject<List<PriceItem>>(json)
                                  .Where(item => IsNameValid(item.name))
                                  .ToList();

If you are worried about memory, then see this answer, which shows how to deserialize a JSON list incrementally from a stream and process each item one by one.

Community
  • 1
  • 1
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300