2

this is not a dup of JSON.NET: Deserializing part of a JSON object to a dictionary

I have JSON { "Count" : 2, "Head" : { "itemId":..., "quality":... }, "Legs" : { "itemId":..., "quality":... } }

I need to deserialize it into a dictionary: IDictionary<GearSlot, Item> If I try to deserialize whole JSON I get an error because it fails to deserialize "Count:2" into <GearSlot, Item>.

GearSlot is an enum, and has ~17+ values. At this time I have defined class:

public class Items {
    property Item Head { get; set; }
    property Item Legs { get; set; }
    ...
}

it works, but not elegant and clunky.

Any suggestions?

2 Answers 2

2

Per this answer and this answer, you could deserialize a partial JSON fragment and then reintegrate.

var root = JObject.Parse(jsonString);
var serializer = new JsonSerializer();
var expectedResult = serializer.Deserialize<ExpectedType>(root["fragment"].CreateReader());

So for you

var items = new Items {
    Head = serializer.Deserialize<Item>(root["Head"])
    , Legs = serializer.Deserialize<Item>(root["Legs"])
};
Sign up to request clarification or add additional context in comments.

Comments

0

You can try using a customer converter. Example: http://weblogs.asp.net/thangchung/archive/2010/08/26/customizing-the-converter-for-json-net.aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.