简体   繁体   中英

JSON Deserialize to generic type

I am writing tests for my controllers (ASP.NET Core), and am receiving back some JSON. I would now like to deserialize it into the correct object so that I can do some assertions against the returned data. There are no exceptions thrown during deserialization, but my Data variable is null.

Here is the code used for the deserialization:

var output = JsonConvert.DeserializeObject(responseString,
                typeof(CrudOperationResult<IEnumerable<ApiResource>>));

This is the CrudOperationResult class:

public class CrudOperationResult<T>
{
    private CrudOperationResult()
    { }

    private CrudOperationResult(CrudResult result, string errorMessage, T data)
    {
        Result = result;
        ErrorMessage = errorMessage;
        Data = data;
    }

    [JsonIgnore]
    public CrudResult Result { get; private set; }

    public bool IsError
    {
        get
        {
            return Result == CrudResult.Error;
        }
    }

    public string ErrorMessage { get; private set; }

    public T Data { get; private set; }
}

And here is the JSON data returned:

{
    "isError": false,
    "errorMessage": null,
    "data": [{
        "id": 1,
        "enabled": true,
        "name": "apiResource1",
        "displayName": "My API",
        "description": null,
        "secrets": null,
        "scopes": [{
            "id": 1,
            "name": "apiResource1",
            "displayName": "My API",
            "description": null,
            "required": false,
            "emphasize": false,
            "showInDiscoveryDocument": true,
            "userClaims": null
        }],
        "userClaims": [{
            "id": 1,
            "type": "role"
        },
        {
            "id": 2,
            "type": "user"
        }]
    }]
}

Issue 1: To deserialize JSON, you need a public constructor with no arguments.

Issue 2: You can't deserialize an interface type ( IEnumerable ).

Try:

var output = JsonConvert.DeserializeObject(responseString,
            typeof(CrudOperationResult<List<ApiResource>>));

Because of the [...] JsonConvert.DeserializeObject thinks data a List<T> Data { get; private set; } List<T> Data { get; private set; } List<T> Data { get; private set; } .

use this function :

List<T> ToJson<T>(byte[] byteArray) where T : new()
{

MemoryStream stream = new MemoryStream(byteArray);


JsonSerializer se = new JsonSerializer();

StreamReader re = new StreamReader(stream);
JsonTextReader reader = new JsonTextReader(re);
    return se.Deserialize<List<T>>(reader);
 }

Try this for this for generic class eg

public class ReturnViewModel<T>

string jsonResponse= cli.UploadString($"{BaseUrl}/API/User/PlaceOrderSubscribeCourse", "{cartdata:" + jsonData + "}");
                    
    var placeOrderResponse = JsonConvert.DeserializeObject<ReturnViewModel<object>>(jsonResponse);
                    if (!placeOrderResponse.IsError)
                    {
                        Response.Redirect("~/ThankYou.aspx");
                    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM