7

I'm trying to map JSON that looks like

"ids": {
    "id": {
        "@value":"6763754764235874140"
    }
}

And I'd like to map it onto a couple of classes that look like

class Property
{
    public Ids Ids { get; set; }
}

class Ids
{
    public string Id { get; set; }
}

So basically I want to stuff the value of ids/id/@value from the JSON document into Ids.Id in the class architecture. From browsing the documentation, I thought I could use something like

[JsonProperty(ItemConverterType=typeof(IdConverter))]
public string Id { get; set; }

and provide a custom JsonConverter subclass named IdConverter. When I do, though, my IdConverter.ReadJson never gets called. What am I doing wrong?

2
  • your property's name is Id, but id in json. It might be a case problem Commented Aug 7, 2012 at 11:01
  • Turns out Json.NET is smart enough to deserialize ids into the Ids property, though it will respect case on serializing unless you tell it not to. Commented Aug 7, 2012 at 11:45

1 Answer 1

16

Looks like the answer was that ItemConverterType is for converting items in an array. Double-annotating the property with JsonProperty and JsonConverter attributes works:

[JsonProperty(PropertyName="id")]
[JsonConverter(typeof(IdConverter))]
public string Id { get; set; }
Sign up to request clarification or add additional context in comments.

3 Comments

Late one here. But I had the same problem, using JsonProperty. I changed it to JsonConverter and it's working, without the need for the extra JsonProperty attribute. Might have just been a bug in an older version but on up-to-date versions (specifically v4), you can just use JsonConverter
It's been quite a while since I messed with this, but I believe the JsonProperty attribute was necessary in order to serialize Id (uppercase first letter) into a JSON field named id (lowercase). Does the newer version handle this correctly without the extra attribute?
It looks as though it does, yes. I think that's probably more a configuration item in the default serializer settings that's changed that in newer versions however. JsonConvert.SerializeObject(new MyClass()) out of the box seems to use the serializable class properties names' as-is.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.