0

I am attempting to create a generic method which will take in an expected type to be converted to and json to convert to that type.

So I have a file that has some json in it:

[{"Index":0,"TickID":null,"Price":0,"PostedDateTime":"\/Date(-62135575200000)\/","ExpirationDateTime":"\/Date(-62135575200000)\/","SellDescription":null,"BuyDescription":null,"AllowSplits":false,"PayCredit":false,"CarID":"1","PaymentID":0,"Source":0,"ModelID":0,"CurrencyCode":null},{"Index":0,"TickID":null,"Price":0,"PostedDateTime":"\/Date(-62135575200000)\/","ExpirationDateTime":"\/Date(-62135575200000)\/","SellDescription":null,"BuyDescription":null,"AllowSplits":false,"PayCredit":false,"CarID":"2","PaymentID":0,"Source":0,"ModelID":0,"CurrencyCode":null}]

so that's a list of 2 objects here that was converted from a C# custom Type (lets call it "Event") to json.

Now I want to get that and deserialize it back to a List

    public static List<T> DeserializeJsonToObject<T>(List<T> objectTypeToDeserializeTo, string jsonToDeserializeToObject)
    {
        var serializedJson = _jsonSerializer.Deserialize(jsonToDeserializeToObject, objectTypeToDeserializeTo);
        return serializedJson;
    }

So I try calling my method here:

jsonInventoryObjects is just that string I grabbed from txt file, the json that I had stored...that I want to convert back to a list of Events.

var inventories = DeserializeJsonToObject(typeof(List<Event>), jsonEventObjects);

I'm not sure how to get my method to work and how to call it. I probably have it completely wrong in the way I'm trying to do this which is why I am posting this. Maybe I'm not even going about it right in terms of syntax in my DeserializeJsonToObject method also.

Goal is to get a reusable generic method that will deserialize any json object (or json list of objects) and also to figure out how to call that method once the syntax is correct for that method.

Ok I played around more, about to try this

public static T DeserializeJsonToObject<T>(string jsonToDeserializeToObject)
{
    var serializedJson = _jsonSerializer.Deserialize<T>(jsonToDeserializeToObject);
    return serializedJson;
}
PositiveGuy
  • 46,620
  • 110
  • 305
  • 471

2 Answers2

0

I came up with something that worked for me:

public static T DeserializeJsonToObject<T>(string jsonToDeserializeToObject)
{
    var serializedJson = _jsonSerializer.Deserialize<T>(jsonToDeserializeToObject);
    return serializedJson;
}
PositiveGuy
  • 46,620
  • 110
  • 305
  • 471
-1

I would suggest looking into JSON.net. Specifically JsonConvert.Deserialize<List<Event>>(list) where list is the JSON string. This will take care of everything for you. It is a widely used .NET library for doing these types of operations. You can go the other way by doing JsonConvert.Serialize(objectsList) where objectsList is a the list of events.

kmacdonald
  • 3,381
  • 2
  • 18
  • 22