JohnD
JohnD

Reputation: 4002

Chose Type to populate from JSON data based on contents of that data

Here's the data I'm trying to deserialize

{
    "elements": [
        {
            "name": "Conference Room 3D",
            "code": "room1",
            "type": 0,
            "bounds": {
                "southWestLat": 42.06258564597228,
                "southWestLng": -88.05174744187781,
                "northEastLat": 42.062638767104781,
                "northEastLng": -88.05170306794393
            }
        },
        // ....
    ]
}

This is quite simple when I'm only expecting a certain kind of data, however I need to be able to put other types of data in that elements array. The type pair is an enumeration which specifies that type of data the object holds. That number then maps to the Class which the object should serialize to.

For Example

I thought I could just write a custom JsonConverter to read the type key, however you cannot rewind the JsonReader object.

Any suggestion for a solution would be greatly appreicated

Upvotes: 0

Views: 150

Answers (2)

L.B
L.B

Reputation: 116168

dynamic dynJson = JsonConvert.DeserializeObject(json);
foreach (var item in dynJson.elements)
{
    if(item.type==0)
    {
        //Do your specific deserialization here using "item.ToString()"
        //For ex,
        var x = JsonConvert.DeserializeObject<MapElementConferenceRoom>(item.ToString());
    }
}

Upvotes: 1

Jason Meckley
Jason Meckley

Reputation: 7591

create a view model that maps directly to the content. then project the specific implementations based on the view model.

Upvotes: 0

Related Questions