[英]Mapping object key values in dictionary and mapping properties with JsonPropertyName
我创建了一个调用外部 API 的基本控制台应用程序。为了测试目的,我的 Main 方法是硬编码的:
static void Main(string[] args)
{
// building a login request
LoginRequest loginRequest = new LoginRequest("myLogin", "myPassword");
LoginService loginService = new LoginServiceImpl();
LoginResponse loginResponse = loginService.Authenticate(loginRequest);
Console.WriteLine("Authentication tryout!");
Console.WriteLine(">> Token : " + loginResponse.AccessToken);
Console.WriteLine(">> Type : " + loginResponse.TokenType);
}
我将 object 传递给服务层。 在这个 class 中,我实现了方法 Authenticate:
public LoginResponse Authenticate(LoginRequest request)
{
LoginResponse returnValue = new LoginResponse();
Uri uri = new Uri("http://www.myapi.com/v1/login");
HttpRequest httpRequest = new HttpRequest();
Task<LoginResponse> loginTask = httpRequest.Authentication(request, uri);
returnValue = loginTask.GetAwaiter().GetResult();
return returnValue;
}
现在这是我在 HttpRequest 中调用 Authentication 方法时遇到的 2 个问题:
public async Task<LoginResponse> Authentication(LoginRequest request, Uri url)
{
var dict = new Dictionary<string, string>();
dict.Add("login", request.login);
dict.Add("password", request.Password);
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json")
);
var req = new HttpRequestMessage(HttpMethod.Post, url) {
Content = new FormUrlEncodedContent(dict)
};
var response = await client.SendAsync(req);
string output = await response.Content.ReadAsStringAsync();
Console.WriteLine(JsonConvert.DeserializeObject(output));
LoginResponse returnValue = JsonConvert.DeserializeObject<LoginResponse>(output);
return returnValue;
}
我的第一个问题是我的词典正在复制词典中的键值。 我有:
Key: "username"
value: "helloWorld"
Key: "username"
value: "helloWorld"
我还尝试将 dictionnary 与这样的东西一起使用:
var dictionary = ToDictionary<string>(request);
foreach(KeyValuePair<string, string> entry in dictionary)
{
dictionary.Add(entry.Key, entry.Value);
Console.WriteLine(entry.Key);
Console.WriteLine(entry.Value);
}
ToDictionnary 如下:
public Dictionary<string, TValue> ToDictionary<TValue>(object obj)
{
var json = JsonConvert.SerializeObject(obj);
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, TValue>>(json);
if (dictionary != null)
{
return dictionary;
}
// handle exception here...
return null;
}
它还复制键值并抛出异常。
我的第二个问题是我不知道如何将 map JsonPropertyName 与属性名称联系起来。 我的调用返回一个字符串,我将其转换为 object。
我的 model 如下:
public class LoginResponse
{
[JsonPropertyName("access_token")]
public string AccessToken { get; set; }
[JsonPropertyName("type_token")]
public string TokenType { get; set; }
public LoginResponse() { }
}
结果,我确实得到了一个字符串,即 i map 为 object 但键未映射:我获得:
{ "access_token": "abcdef", "type_token": "Bearer" }
虽然我期望:
{ "AccessToken": "abcdef", "TokenType": "Bearer" }
我用序列化解决了我的问题。 我正在使用 System.Text.Json.Serialization... 我在我的 model 中使用 Newtonsoft.Json 代替。
我还更改了注释:
[JsonPropertyName("access_token")]
和:
[JsonProperty(PropertyName = "access_token")]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.