我正在使用这个接口
https://test.httpapi.com/api/domains/available.json?auth-userid=0&api-key=key&domain-name=domain1&domain-name=domain2&tlds=com&tlds=net
当我在此 api 中传递一些参数时,它会以这种格式为我输出
{
"apple.com":{"status":"regthroughothers","classkey":"domcno"},
"asdfgqwx.com":{"status":"available","classkey":"domcno"},
"microsoft.org":{"status":"unknown"},
"apple.org":{"status":"unknown"},
"microsoft.com":{"status":"regthroughothers","classkey":"domcno"},
"asdfgqwx.org":{"status":"unknown"}
}
这种 Json 格式对我来说很奇怪。所以我想像这样更改 Json 格式
[{
"name": "apple.com",
"status": "regthroughothers",
"classkey": "domcno"
},
{
"name": "asdfgqwx.com",
"status": "available",
"classkey": "domcno"
},
{
"name": "microsoft.org",
"status": "unknown",
"classkey": ""
},
{
"name": "apple.org",
"status": "unknown",
"classkey": ""
},
{
"name": "microsoft.com",
"status": "regthroughothers",
"classkey": "domcno"
},
{
"name": "asdfgqwx.org",
"status": "unknown",
"classkey": "domcno"
}]
我正在使用此代码来使用 API。
protected string GET(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
您可以使用 Json.Net 的 LINQ-to-JSON API 将 JSON 从一种格式转换为另一种格式,如果这是您真正想要做的。 这是一种可以做到这一点的方法:
public static string TransformJson(string originalJson)
{
return new JArray(
JObject.Parse(originalJson).Properties().Select(jp =>
{
var jo = new JObject((JObject)jp.Value);
jo.AddFirst(new JProperty("name", jp.Name));
return jo;
})
).ToString();
}
小提琴:https://dotnetfiddle.net/BoU8W5
我在使用您的 GET 方法连接到 API 时遇到问题。它总是返回连接失败...
无论如何,api 实际上返回了一个字典类型 json。因此,您必须创建一个类并相应地反序列化 json 响应。
public class UrlObject
{
public string status { get; set; }
public string classkey { get; set; }
}
//string jsonResponse = GET("https://test.httpapi.com/api/domains/available.json?auth-userid=0&api-key=key&domain-name=domain1&domain-name=domain2&tlds=com&tlds=net");
string jsonResponse = "{"apple.com":{"status":"regthroughothers","classkey":"domcno"},"asdfgqwx.com":{"status":"available","classkey":"domcno"},"microsoft.org":{"status":"unknown"},"apple.org":{"status":"unknown"},"microsoft.com":{"status":"regthroughothers","classkey":"domcno"},"asdfgqwx.org":{"status":"unknown"}}";
Dictionary<string, UrlObject> urlDictionary = JsonConvert.DeserializeObject<Dictionary<string, UrlObject>>(jsonResponse);
请注意,json 反序列化已成功,现在您可以访问这些值。由于我看不到将 json 格式转换为另一种格式的意义,因此我将其留给您。
除非您控制服务器,或者服务器公开了 API 来执行此操作,否则您无法更改服务器返回的响应。
如果你想要一个不同的对象模型,例如一个对象数组而不是一个对象字典,如你的问题中所述,那么你需要编写一些代码来从API模型映射到你想要在应用程序/库中实际使用的模型。