gpt4 book ai didi

c# - 返回 json 的 字符串

转载 作者:行者123 更新时间:2023-11-30 22:59:59 25 4
gpt4 key购买 nike

这让我很沮丧,谷歌现在不是我的 friend 。

我有一个GET方法返回参数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);
}

T 是字符串类型,我只想返回纯 JSON 数据。

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

但是当我将 JSON 放入 DeserializeObject 时,我收到以下错误消息:

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

当我将它作为 List 返回时它会起作用但就像输入字符串一样,它会给出错误。

最佳答案

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

如果你想要纯 JSON 数据,为什么要调用 DeserializeObject

听起来你想要这样的东西:

...
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);

双重转换 (T)(object) 是必要的,因为我们知道 T 是字符串类型,但编译器不知道't.

关于c# - 返回 json 的 <T> 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51873121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com