Joey Erdogan
Joey Erdogan

Reputation: 184

Return <T> string for json

Its frustrating me and google is not my friend right now.

I have a GET method return parameter T

public T GET(string path, string filter = "", string select = "")
    {
        //Check for accesstoken
        oAuthHelper.GetAccessToken();

        //request token
        var restclient = new RestClient(_url);
        RestRequest request = new RestRequest(string.Format("api/v1/{1}/{0}", path, Global._DIVISION)) { Method = Method.GET };

        request.AddHeader("Accept", "application/json");
        request.AddHeader("Content-Type", "application/text");

        //GUID FILTER"
        //string.Format("ID eq guid'{0}'",  "6526d916-173b-4c23-b3da-068c70d6a867")

        if (!string.IsNullOrEmpty(filter))
            request.AddParameter("$filter", filter, ParameterType.QueryString);

        if (!string.IsNullOrEmpty(select))
            request.AddParameter("$select", select, ParameterType.QueryString);

        request.AddParameter("Authorization", string.Format("Bearer " + Global._ACCESTOKEN),
        ParameterType.HttpHeader);

        var tResponse = restclient.Execute(request);
        var responseJson = tResponse.Content;



        JObject obj = JObject.Parse(responseJson);

        JArray categories = (JArray)obj["d"]["results"];

        if (categories.Count == 0)
        {
            return default(T);
        }

        string JSON = categories.ToString();

        return JsonConvert.DeserializeObject<T>(JSON);
    }

The T is type of string, i just want to return the plain JSON data.

            //HttpClientWrapper
        using (var client = new HttpClientWrapper<string>())
        {
            var data = client.GET(_URL, null, null);
            return data.ToString();
        }

But when i put the JSON in the DeserializeObject i get following error message:

Additional information: Unexpected character encountered while parsing value: [. Path '', line 1, position 1.

When i return it as List it will work But just as type string it will give that eror.

Upvotes: 2

Views: 617

Answers (1)

Heinzi
Heinzi

Reputation: 172220

The T is type of string, i just want to return the plain JSON data.

If you want the plain JSON data, why do you call DeserializeObject?

It sounds like you want something like that:

...
string JSON = categories.ToString();

// exit early, if we want the plain JSON data
if (typeof(T) == typeof(string))
    return (T)(object)JSON;

return JsonConvert.DeserializeObject<T>(JSON);

The double cast (T)(object) is necessary, since we know that T is of type string, but the compiler doesn't.

Upvotes: 2

Related Questions